P
prasadmpatil
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";
}
I am getting the following output. Could somebody please explain what
is happening in my program. I am thoroughly confused.
---------------------------------------Output------------------
Vector test begin
value: 1
value: 2
value: 3
value: 4
value: 0
value: 41
value: 1
value: 2
value: 3
value: 4
value: 5
value: 4
value: 5
Vector test end
----------------------------------------------End of
Output--------------------------------------
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";
}
I am getting the following output. Could somebody please explain what
is happening in my program. I am thoroughly confused.
---------------------------------------Output------------------
Vector test begin
value: 1
value: 2
value: 3
value: 4
value: 0
value: 41
value: 1
value: 2
value: 3
value: 4
value: 5
value: 4
value: 5
Vector test end
----------------------------------------------End of
Output--------------------------------------