Previously today, I asked a question about implementing a Sieve of Eratosthenes with 2D arrays and was told by a few people to use vectors instead. The only problem is I had no idea how to use Vectors in C++.
I have rewritten my program today using a vector instead of a 2D array and it was going quite well until near the end of the program, where I receive the following error:
sieve.h: In function ‘void printPrimes(std::vector*, int)’: sieve.h:42:20: error: no match for ‘operator<<’ in ‘std::cout << *(primes + ((unsigned int)(((unsigned int)i) * 12u)))’
I have never received this kind of error message before so I am unsure of how to fix this.
Here is my revised code:
sieve.h
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <vector>
using namespace std;
vector<int> calc_primes(int);
void printPrimes(int[]);
vector<int> calc_primes(int max)
{
vector<int> primes;
for(int i = 2; i < max; i++)
{
primes.push_back(i);
}
// for each value in the vector
for(int i = 0; i < primes.size(); i++)
{
//get the value
int v = primes[i];
if (v!=0) {
//remove all multiples of the value
int x = i+v;
while(x < primes.size()) {
primes[x]=0;
x = x+v;
}
}
}
return primes;
}
void printPrimes(vector<int>* primes, int size)
{
int primearray[size];
for(int i = 0; i < size; i++)
{
cout<<primes[i]<<endl;
}
}
sieve.cpp
#include "sieve.h"
using namespace std;
int main()
{
int max;
cout<<"Please enter the max amount of prime numbers:"<<endl;
cin>>max;
vector<int> primes = calc_primes(max);
printPrimes(primes, max);
return 0;
}