STL C++Iterators

Hello! Please tell me if it is possible to store iterators from vector for a long time, for example, so that it can be dereferenced in the future and not get errors (vector iterators incompatible).

Trying to store iterators vector<char *>in another container vector<vector<char *>::iterator>. Is it possible to delete vector<char *> elements via stored iterators?:

vector<char *> a;
vector<vector<char *>::iterator> b;
a.push_back("sasl");
a.push_back("wqe");
...
a.push_back("sasl");
for (vector<char *>::iterator i=a.begin(); i!=a.end(); i++) {
   b.push_back(i);
}
...
a.erase( *( b.begin() ) );

The example may be working, I have an error somewhere in another program. I just wonder if it could be, so that the iterators change after erase(), for example, and is such a {[10] normal at all]}code, acceptable, good tone?

In a problem with an error, I use

map<vector<char *>::iterator, vector<vector<char *>::iterator>> c

Let there be some

vector<char *>::iterator d

I appeal:

for (vector<vector<char*>::iterator>>::iterator it=c[d].begin(); it!=c[d].end(); it++) {
   //b из предыдущего листинга
   cout << *b[*it] << endl;
}

Instead of char*, the program with the error has a different structure.

Author: who-e, 2014-07-19

1 answers

See. Iterators must be short-lived. The reason is that any operation that modifies an stl container invalidates iterators that point to elements of that container.

Some operations leave valid some iterators of some container types. For example, deleting an element from std::vector is guaranteed not to invalidate iterators pointing to elements before the deleted element. But counting on it, especially implicitly , is a bad idea: tomorrow the preceding element will randomly become the next one, or std::vector will change to std::map, and you will wonder who you have trampled on from memory.

Just don't use iterators outside of the context of a short operation.

 5
Author: VladD, 2014-07-19 21:11:38