I've recently inherited a project primarily done in C++, so this is my first real exposure to it. I'm wondering if I may have a problem erasing a vector's elements from within a loop bounded by the vector's begin()
and end()
.
Here's (essentially) what I've been trying to do:
for (vector<double>::iterator i = distance.begin(); i < distance.end(); i++) {
for (vector<double>::iterator j = i + 1; j < distance.end(); j++) {
/* code to assemble *i, *j, and some other values, say *x & *y
(also iterators) assumed to be in the distance vector */
vector< vector<double >::iterator remove;
remove.push_back(i); remove.push_back(j);
remove.push_back(x); remove.push_back(y);
sort(remove.begin(), remove.end());
for (int r = remove.size() - 1; r >= 0; r--) {
distance.erase(remove.at(r));
}
}
}
For what I'm testing it on, this appears to work. However, I'm concerned that's just because of a fluke and this solution shouldn't be used. Does distance.end()
get reset at the beginning of each loop, or does C++ just check with the initial value?