Re: Query regarding iterators and vector
In article <1ce7647b-4099-41b0-be32-
3e25756152bb@m45g2000hsb.googlegroups.com>, prasadmpatil@gmail.com
says...
I am new STL programming.
I have a query regarding vectors. If I am iterating over a vector
using a iterator, but do some operations that modify the size of the
vector. Will the iterator recognize this?
I wrote the following program to test this out.
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
cout<<"Vector test begin"<<endl;
vector<int>::iterator iter0;
for(iter0=a.begin(); iter0!=a.end(); iter0++)
{
cout << "\n value: " << (*iter0)<<endl;
if(*iter0 == 2)
{
a.push_back(4);
a.push_back(5);
}
}
cout<<"Vector test end";
}
A push_back on a vector invalidates all iterators into that vector.
However, directly using an iterator in a loop is a sign that you're not
really using algorithms as intended. In this case you're adding the
sequence '4,5' each time you find a '2' in the input. I'd do that
something like this:
int n = std::count(a.begin(), a.end(), 2);
for (int i=0;i<n;i++) {
a.push_back(4);
a.push_back(5);
}
It's also possible that you only really intended to add the '4,5' once,
regardless of how many times '2' was found in the input. In that case,
I'd do something like:
if (std::binary_search(a.begin(), a.end(), 2)) {
a.push_back(4);
a.push_back(5);
}
or, if the fact that the input was sorted was really just an accident,
and it could be in random order:
if (std::find(a.begin(), a.end(), 2)!=a.end()) {
a.push_back(4);
a.push_back(5);
}
--
Later,
Jerry.
The universe is a figment of its own imagination.