vector iterators

I have the following program:

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
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

vector<int> arrayOfInts;

void constructNewInt(int num)
{
	arrayOfInts.push_back(num);
}

void addNewInts()
{
	vector<int>::iterator it = arrayOfInts.begin();	
	
	constructNewInt(3);	
	
	arrayOfInts.erase(it);
}

int main(int argc, char **argv)
{
	
	arrayOfInts.push_back(1);
	//array.push_back(2);
	
	addNewInts();
	
	for(vector<int>::iterator it = arrayOfInts.begin(); it != arrayOfInts.end(); it++)
		cout << *it << ' ';
	
	cout << endl;
	
}


I don't understand why this gives me a seg fault. But if I change function addNewInts() to this:

1
2
3
4
5
6
7
8
void addNewInts()
{
	vector<int>::iterator it = arrayOfInts.begin();	
	
	arrayOfInts.erase(it);	
	
	constructNewInt(3);	
}


it works fine.

thanks,
mike
Probably because the push_back in the first case caused an internal reallocation in the vector thus all its iterators were invalidated. To see if this is the case, reserve a bunch of space in the vector at the beginning of main by doing arrayOfInts.reserve(10); for example and try the first version of addNewInts(). That should side step the seg fault.
Last edited on
Topic archived. No new replies allowed.