返回bool和从矢量

Mic*_*rst 4 c++ stl vector

在以下代码中:

class SomeClass {
    vector<int> i;
    vector<bool> b;

public:
    int& geti() {return i[0];}
    bool& getb() {return b[0];}
};
Run Code Online (Sandbox Code Playgroud)

如果你注释掉getb(),代码编译得很好.显然,将引用返回到int存储在向量中的引用是没有问题的,但是你不能用a做bool.

为什么是这样?

Jam*_*lis 11

std::vector<bool>是"特别的".它将其元素存储为位数组,这意味着元素不是可单独寻址的,并且您无法获得对元素的引用.

std::vector<bool>迭代器,它operator[]和它的其他成员函数返回代理对象,这些代理对象提供对元素的访问,而不需要bool存储实际对象.

如果您需要能够访问单个元素,请考虑使用std::vector<char>或定义boolchar(signed char或者unsigned char,如果您关心签名)支持的类似枚举.

  • 好吧,谷歌搜索后,它似乎被提出,但C++标准委员会击落了它. (2认同)