Reputation: 45
So.. I have 2 vectors: xmax and ymax, which represent the x and y coordinates of a list of points. I want to delete the variables in which xmax[i]==xmax[i-1] and ymax[i]==ymax[i-1] (so... to sum up, I want to delete repeated points which have same coordinates). This is the code I am using:
std::vector<double> xx, yy;
for (int i = 0; i < xmax.size(); i++) {
if (i > 0 && xmax[i] == xmax[i - 1] && ymax[i]==ymax[i-1])
continue;
xx.push_back(xmax[i]);
yy.push_back(ymax[i]);
}
But I would like to know if there is a simple way of deleting the variables without creating a new vector for this.
Upvotes: 0
Views: 76
Reputation: 15446
I'd advise switching to a single vector of pairs of ints (instead of two separate vectors):
std::vector<std::pair<int, int>> points = {{1, 1}, {5, 2}, {5, 2}, {7, 10}};
Then you can make use of std::unique()
.
If you define a comparator function:
bool point_compare(const std::pair<int, int> &p1, const std::pair<int, int> &p2) {
return p1.first == p2.first && p1.second == p2.second;
}
Then you can use std::unique()
like:
auto last = std::unique(points.begin(), points.end());
points.erase(last, points.end());
See it in action here: https://ideone.com/fZM9b2
Upvotes: 2