vectors

I'm not sure what i am doing wrong, can someone please let me know.
im trying to print the prime numbers, so i put the numbers into the vector and then erase the non prime numbers. if i comment the break statement i get runtime error saying out of bound, but if i don't comment it out it prints the primes but it also prints the multiples of 3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void Eratos( int length, vector< int > &v )
{
	int i;
	for (i=0; i<length; ++i)
	{
		v.push_back(i);
		cout <<v[i];
	}
	cout <<endl;
	

	for(unsigned int i=3; i<v.size(); ++i) 
	{
		for(unsigned int j= 2; j <i; ++j) 
		{

		if (v[i] %j ==0 ) 
			{
				v.erase( v.begin( ) +i );
				break;
			}
		}
	}

}
Last edited on
Do not put all numbers in the vector in the first place. Add only the primes. That should be both less error-prone and more efficient.

Please, use the code tags for readability. See http://www.cplusplus.com/articles/jEywvCM9/
You should note that there are many examples of how to find primes on the internet :/
Thanks keskiverto and sorry for not reading up before.
Topic archived. No new replies allowed.