使用自定义 C++ 头文件时出现编译时错误 - "std_lib_facilities.h"

Compile-time error while using custom C++ header file - "std_lib_facilities.h"

我是 C++ 新手,我正在使用这本书进行学习 - Programming Principles & Practice using C++ by Bjarne Stroustrup,第 1 版。作者为每个程序 - 示例、练习或练习都使用头文件 std_lib_facilities.h (here)。

我正在尝试解决第 4 章中的问题 13 -

Create a program to find all the prime numbers between 1 and 100. There is a classic method for doing this, called the "Sieve of Eratosthenes." U you don't know that method, get on the web and look it up. Write your program using this method.

当我尝试编译我的程序时(我使用的是 Visual Studio 2013),这里 -

// Sieve of Eratosthenes

#include "std_lib_facilities.h"

int main()
{
    int max = 100, i = 0, j = 0, total = 0;
    vector<bool> primes(max + 1, true);

    // Find primes using Sieve of Eratosthenes method
    primes[0] = false;
    primes[1] = false;
    for (i = 0; i <= max; ++i){
        if (primes[i] == true){
            for (j = 2; i * j <= max; ++j){
                primes[i * j] = false;
            }
        }
    }

    // Show primes
    cout << "\n\nAll prime numbers from 1 to " << max << " -\n\n";
    for (i = 0; i < primes.size(); ++i)
        if (primes[i] == true){
            cout << i << " ";
            ++total;
        }
    cout << "\n\nTotal number of prime numbers == " << total << "\n\n";

    keep_window_open();
    return 0;
}

它显示了这个我无法理解的错误 -

1>  13_4exercise.cpp
1>c:\users\i$hu\documents\visual studio 2013\projects\c++ development\c++ development_4exercise.cpp(23): warning C4018: '<' : signed/unsigned mismatch
1>c:\users\i$hu\documents\visual studio 2013\projects\c++ development\c++ development\std_lib_facilities.h(88): error C2440: 'return' : cannot convert from 'std::_Vb_reference<std::_Wrap_alloc<std::allocator<char32_t>>>' to 'bool &'
1>          c:\users\i$hu\documents\visual studio 2013\projects\c++ development\c++ development\std_lib_facilities.h(86) : while compiling class template member function 'bool &Vector<bool>::operator [](unsigned int)'
1>          c:\users\i$hu\documents\visual studio 2013\projects\c++ development\c++ development_4exercise.cpp(11) : see reference to function template instantiation 'bool &Vector<bool>::operator [](unsigned int)' being compiled
1>          c:\users\i$hu\documents\visual studio 2013\projects\c++ development\c++ development_4exercise.cpp(8) : see reference to class template instantiation 'Vector<bool>' being compiled

这个错误是什么意思,如何解决?

此问题与您的 header 有关。

如果将此包含替换为纯标准 headers:

,它将编译
#include <iostream>
#include <vector>
using namespace std;  // for learning purpose

并将keep_window_open()替换为cin.get()

您的库 "std_lib_facilities.h" 正在使用 vector 的自定义实现,它没有 vector<bool> 专用模板。

专用模板使用 allocator<bool>vector<bool>::reference 作为 operator[] 的 return 值。

在你的情况下,它使用默认分配器,它是 returning std::_Vb_reference<std::_Wrap_alloc<std::allocator<char32_t>>> 来自 operator[] - 因此你的问题。