I'm working through Bjarne Stroustrup's [url=
http://www.stroustrup.com/Programming/]latest book[/url] (aimed at teacher people C++ from the ground up). Enjoying it quite a lot. Haven't really encountered many problems with the exercises up until now; Chapter 04, to be precise.
Anyway, the point of this exercise is to use all the skills learnt from previous chapters (vectors, loops, conditional-statements etc) to generate a list of prime numbers using the "Sieve of Eratosthenes" algorithm.
Here's the source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
// the "Sieve of Eratosthenes"
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// create empty vector to hold real numbers
vector<int> real_numbers;
// use "for" loop to populate vector
for (int i = 2; i <= 100; ++i)
real_numbers.push_back(i);
// use "for" loop to work each element of vector
for (int j = 0; j < real_numbers.size(); ++j)
{
// initialise first prime
int prime = real_numbers[j];
// use "for" loop to go through multiples of prime
for (int multiple = 2; prime*prime <= 100; ++multiple)
// remove current multiple of prime
real_numbers.erase(real_numbers[multiple*prime]);
}
// use "for loop" to print remaining (prime) integers
for (int k = 0; k < real_numbers.size(); ++k)
cout << real_numbers[k] << " ";
return 0;
}
|
When I try compile it with g++, however, I get the following error message.
g++ main.cpp -o main
main.cpp: In function ‘int main()’:
main.cpp:26: error: no matching function for call to ‘std::vector<int, std::allocator<int> >::erase(int&)’
/usr/include/c++/4.4/bits/vector.tcc:133: note: candidates are: __gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> > std::vector<_Tp, _Alloc>::erase(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >) [with _Tp = int, _Alloc = std::allocator<int>]
/usr/include/c++/4.4/bits/vector.tcc:145: note: __gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> > std::vector<_Tp, _Alloc>::erase(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, __gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >) [with _Tp = int, _Alloc = std::allocator<int>]
|
the
erase() member function belonging to
vector seems to be the problem. The only member function I know of that removes elements is
pop_back() but that only removes an element from the end of the vector - not really the desired effect.
Any comments/suggestions?