Suppose I have the following vector:
The vector is a vector of pairs, and we are comparing based on the first element.
[(1,0),(0,1),(3,2),(6,3),(2,4),(4,5),(7,6),(5,7)]
I want to erase all elements in a specific range except the largest.
For example, if the range was $l = 2$ and $r = 5$, then the output:
[(1,0),(0,1),(6,3),(7,6),(5,7)]
Now if we do this again to the output array for $l = 1$, $r = 4$, then the output:
[(1,0),(7,6)]
I found this which I thought would be useful here, but I don't know how to make it work for pairs.
Here is my attempt:
int main(int argc, char const *argv[]) {
int N;
cin >> N;
vector< pair<int,int> > vector_of_pairs(N);
for (int i = 0; i < N; i++) {
int input;
cin >> input;
vector_of_pairs[i] = make_pair(input, i);
}
int l, r;
cin >> l >> r;
int max_in_range = vector_of_pairs[l].first;
for (int i = l+1; i <= r; i++) {
if (vector_of_pairs[i].first > max_in_range) {
max_in_range = vector_of_pairs[i].first;
}
}
for (int i = l; i <= r; i++) {
if (vector_of_pairs[i].first != max_in_range) {
vector_of_pairs.erase(vector_of_pairs.begin() + i);
}
}
printf("[");
for(int i = 0; i < vector_of_pairs.size(); i++) {
printf("(%d,%d)", vector_of_pairs[i].first, vector_of_pairs[i].second);
}
printf("]\n");
}
For the following input:
8
1 0 5 6 2 3 7 4
1 3
This is the output:
[(1,0)(5,2)(6,3)(3,5)(7,6)(4,7)]
But it should be
[(1,0)(6,3)(3,5)(7,6)(4,7)]
Also, for certain inputs I get seg faults so how can I safe guard against that?