无法使用Bjarne Stroustrup的《编程手册》

时间:2018-07-12 02:09:13

标签: c++ compiler-errors sieve-of-eratosthenes

我正在研究Bjarne Stroustrup的 Programming:使用C ++的原理和实践(第二版),当我尝试使用{{1时,使用his custom header file, std_lib_facilities.h时遇到了问题}}。

我正在练习第13页的练习13。 130,它允许用户指定上限 n ,然后使用Eratosthenes筛子查找[2 .. n ]之间的所有素数。我以为我会使用vector<bool>将标记存储在数字上(无论它们是否是合成的)。但是,这不起作用。这是我的代码:

vector<bool>

但是,当我尝试使用g ++(// 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'; } )进行编译时,出现以下错误:

g++ (SUSE Linux) 7.3.1 20180323 [gcc-7-branch revision 258812]

我不确定筛子是否正确,因为我无法对其进行编译以进行测试,但是主要是我试图克服该错误。是否有其他替代方法可以解决此问题,因为不允许使用> 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 ^~~~~~~~ ,这是头文件的问题还是我做错了其他事情?

0 个答案:

没有答案