Hi all,
I am currently trying to implement a Sieve of Eratostheneses in C++ as part of a book I am learning. The objective is to find all of the prime numbers between 1 and n in a list. To achieve this, I am using two vectors, one that stores the numbers to check, and another to hold the actual numbers.
Here is the code for where I am up to:
The problem I currently have, is that I want to delete the number from the vector instead of just zeroing it. I have tried to use erase(primes.begin() + j) though this will produce an out of range error.Code:#include <iostream> #include <vector> #include <algorithm> using namespace std; int main(int argc, char** argv[]) { vector<int> nums; vector<int> primes; int n, numToCheck; cout << "Please enter n: "; cin >> n; //populate num list for(int i = 2; i < n; i++) { nums.push_back(i); primes.push_back(i); } //move through array, eliminating multiples for(int i = 0; i < nums.size(); i++) { //assign number to check multiples of numToCheck = nums[i]; //cycle through vector and delete multiples for(int j = 0; j < primes.size(); j++) { if(primes[j] != numToCheck && primes[j]%numToCheck == 0) { primes[j] = 0; //Number isn't prime } } } for(int i = 0; i < primes.size(); i++) { cout << primes[i] << endl; } return 0; }
Can somebody point me in the correct direction please?



LinkBack URL
About LinkBacks



