Reputation: 862
I want to call clear
when loop to visit the vector
. I think this will be dangerous, but in my experiment code below, it seems ok to run, it just stop the loop when i called clear
.
#include <bits/stdc++.h>
using namespace std;
int main() {
std::vector<int> a = {1,2,3,4,5};
for (size_t i = 0; i < a.size(); ++i) {
a.clear(); // just run once, then loop exited
cout << "i = " << i << endl;
}
}
Is there anything I don't know about the risk? could you help on this?
Upvotes: 1
Views: 83
Reputation: 118340
There is a very, very major temptation that when you have a loop that looks like this:
for (size_t i = 0; i < a.size(); ++i) {
then you will be under the impression that looking at a[i]
and/or modifying it, freely, inside the loop, whenever you have an urge to do so, is perfectly acceptable.
And it is. Unless you already did a
a.clear();
Alone, by itself, there's nothing wrong with just the code you showed. It's defined behavior. But as soon as a
is clear()
ed, doing something with a[i]
becomes a no-no, inside the loop. But resistance is futile. At some point it's a near certainty that you'll forget that you clear()
ed the vector, decide to take a peek at a[i]
, and have to deal with demons flying out of your nose.
If your goal is to stop the loop, a simple break
will do. If there is a separate reason to clear()
the vector, do so, but immediately break
from the loop as well, to avoid giving in to the temptations of creating nasal demons.
Upvotes: 2