I'm trying to implement the Sieve of Eratosthene in C++. However after several attempts at this I always get runtime errors. I'm thinking this has to do with the state of iterators being used get corrupted somewhere. I can't put my finger on it though. Here is my code:
//Sieves all multiples of the current sequence element
bool multiple_sieve(std::list<int>& num_list)
{
std::list<int>::iterator list_iter(num_list.begin());
std::list<int>::reverse_iterator last_element_iter(num_list.rbegin());
for(std::list<int>::iterator elements_iter(++list_iter);
elements_iter != num_list.end();)
{
if((*elements_iter % *list_iter == 0) &&
(*elements_iter <= *last_element_iter) && (*list_iter != 1))
num_list.erase(elements_iter);
else ++elements_iter;
}
return true;
}
std::list<int>& prime_sieve(std::list<int>& num_list)
{
for(std::list<int>::iterator list_iter(num_list.begin());
list_iter != num_list.end(); ++list_iter)
multiple_sieve(num_list);
return num_list;
}
What I'm doing wrong? What's generating the runtime errors?
Update: When I run this in my tests I get an error with the message "list iterators are not compatible".