I'm working through Bjarne Stroustrup's Programming: Principles and Practice Using C++ (2nd ed.) book and ran into a problem using his custom header file, std_lib_facilities.h
when I try to use a vector<bool>
.
I'm working on exercise 13 on p. 130, which is to allow the user to specify an upper bound, n, and then to find all of the primes between [2..n] using the Sieve of Eratosthenes. I figured I'd use a vector<bool>
to store the marks on the numbers (whether or not they are composite). However, that is not working. Here is my code:
// exercise 13 on p. 130
// using Sieve of Eratosthenes to find prime numbers from 2..max
#include "../include/std_lib_facilities.h"
vector<int> sieve_of_Eratosthenes(int max)
{
// initialize all values from 0..n to false
vector<bool> is_composite;
for (int i = 0; i < max + 1; ++i)
is_composite[i] = false;
vector<int> primes;
int sqrt_max = sqrt(max);
for (int m = 2; m <= sqrt_max; ++m) {
if (!is_composite[m]) {
primes.push_back(m);
for (int k = m * m; k <= max; k += m)
is_composite[k] = true;
}
}
for (int m = sqrt_max; m <= max; ++m)
if (!is_composite[m])
primes.push_back(m);
return primes;
}
int main()
{
int max = 100;
cout << "Enter maximum value for Prime Finder: ";
cin >> max;
vector<int> primes = sieve_of_Eratosthenes(max);
for (int p : primes)
cout << p << '\n';
}
However, when I try to compile using g++ (g++ (SUSE Linux) 7.3.1 20180323 [gcc-7-branch revision 258812]
), I get the following error(s):
> g++ exercise13.cpp -o bin/exercise13
In file included from exercise13.cpp:4:0:
../include/std_lib_facilities.h: In instantiation of ‘T& Vector<T>::operator[](unsigned int) [with T = bool]’:
exercise13.cpp:11:17: required from here
../include/std_lib_facilities.h:88:36: error: cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type ‘bool’
return std::vector<T>::operator[](i);
~~~~~~~~~~~~~~~~~~~~~~~~~~^~~
In file included from /usr/include/c++/7/vector:65:0,
from ../include/std_lib_facilities.h:37,
from exercise13.cpp:4:
/usr/include/c++/7/bits/stl_bvector.h:80:5: note: after user-defined conversion: std::_Bit_reference::operator bool() const
operator bool() const _GLIBCXX_NOEXCEPT
^~~~~~~~
I'm not sure if the sieve is correct or not as I have not been able to compile it to test, but mainly I'm trying to just get past this error. Is there an alternate way I should be solving this because vector<bool>
is not allowed, is this an issue with the header file, or did I do something else wrong?