Problem with the <vector> container

I am trying to make a program which reads a vector of integers (including the length) and after every even number I want to insert a value (2011). I solved this problem with a function and a few for-loops but I want to make work by using the functions provided in STL.
Here's what I have until now:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
#include<vector>
using namespace std;
int main()
{
    vector<int> x;
    vector<int>::iterator it;
    unsigned int i,n,k;

    cout<<"n="; cin>>n;
    for(i = 0; i<n; i++)
    {
        cout<<"Enter the value: ";
        cin>>k;
        x.push_back(k);
    }

    for(i = 0, it = x.begin(); it<x.end(); i++, it++)
    {
        if(x[i]%2==0)
        {
            x.insert(it+1, 2011);

        }
        
    }
    for(it = x.begin(); it<x.end(); it++)
     cout<<*it<<" ";
    return 0;
}

It doesn't work at all and I don't know how to fix it. Thank you.
insert() invalidates the iterator. Call C++ a high level language?
You "fix" it by using a temporary std::vector.

1
2
3
4
5
6
7
8
9
10
11
	vector<int> temp;

	for (it = x.begin(); it != x.end(); ++it)
	{
		temp.push_back(*it);

		if (*it % 2 == 0)
			temp.push_back(2011);
	}

	x = temp; // bye old vector 

He could reset the iterator whenever he calls insert, and then place it back to the appropriate spot. I don't know if this would be any easier though.
Thank you very much! I didn't read carefully the description of that function. Thanks again!
Topic archived. No new replies allowed.