开发者

Invalidating loop bounds

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?


for-loop will evaluate i < distance.end() on each loop. The problem is in distance.erase, it will invalidate i, so the result of i++ is undefined.


distance.end() is always accurate to the current state of the vector.

for() loops always re-evaluate the condition on every loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜