Hi, i am trying to write a program which calculates the sum of the prime numbers below a specific limit using an algorithm called the Sieve of Eratosthenes(Wikipedia it). I am getting an error though when i run my program. It says debug assertion fail and something how the iterator are incompatible. I have worked much with vectors before, any help??

Here is my code:

#include<iostream>
#include<vector>
#include <numeric>

using namespace std;

int main(){

unsigned int j = 10;
vector<unsigned int> NumList;
for (int i=3; i<=j; i+=2) NumList.push_back(i); // populating vector with odd numbers

vector<unsigned int>::iterator it; // creating an iterator to access values in the vector
vector<unsigned int>::iterator p;
unsigned int q = 0;

while(p<NumList.end()){

p = NumList.begin() + q; // sets p to the first number in the vector which is left and has not been tested

for (it = NumList.begin()+1; it < NumList.end(); it++) {

if(*it%*p == 0) NumList.erase(it); // erases numbers of the vector which are multiples of p

}
q++; // interating q
}

cout << std::accumulate( NumList.begin(), NumList.end(), 0 ) << endl; // summing final values left in the array

system("pause");
return 0;
}

line 17: p is an uninitialized iterator so the while statement fails. You might want to initiazlize it to p = NumList.begin() before line 17.

That won't fix the problem either. Another problem: what happens when the number of elements in NumList is less than the value of q? In the beginning there will be 4 elements in NumList. When line 23 erases one of the numbers then NumList will have only 3 elements, yet the value of q is incremented by 1. Eventually q will exceed the number of elements in the vector.

A third problem is that erase() will invalidate the value of iterator it in the for loop on line 21. When erase() is called the iterator it has to be re-initialized to NumList.begin() to start the for loop all over again.

Edited 5 Years Ago by Ancient Dragon: n/a

ok, thanks for the tips, i've fixed the first two problems but im having trouble understanding the third. I thought that the for loop in line 21 would reinitialize and itterate "it" but i guess it doesnt work that way...

I've tried to modify the for loop, but now im getting another error about the vector itterators being incompattible, not really sure what that means but here is the for loop:

for (int w=1; w<NumList.size(); w++) {
			
			it = NumList.begin()+w;	// w is being used to itterate "it" through the vector
			if(*it%*p == 0) NumList.erase(it);  // erases numbers of the vector which are multiples of p
	
		}

I was able to get it working,just had for fine-tune some of the limits. Thanks for the help though.

This article has been dead for over six months. Start a new discussion instead.