类构造函数初始化矢量向量

问题描述:

我想在我的构造函数里初始化一个向量bool矢量。类构造函数初始化矢量向量

这是我的课:

class MyClass{ 
public: 
    MyClass(const OtherClass&g): 
     g(g), count(g.node_count(), std::vector<bool>(16))){} 


private: 
    const OtherClass&g; 
    std::vector<std::vector<bool>>count; 
}; 

但是当我尝试初始化count我得到这个错误:

error: no match for call to ‘(std::vector<std::vector<bool> >) (int)’ 
+0

无关,[尽量避免](https://isocpp.org/blog/2012/11/on-vectorbool)'矢量',它是一个混合怪物。您可以使用['std :: bitset '](http://en.cppreference.com/w/cpp/utility/bitset)。 – vsoftco

+0

奇怪的为什么使用一个载体,如果你知道你需要16布尔?为什么'const OtherClass&'?使用此设计时遇到麻烦。当你将一个对象(A)引用给另一个对象(B)时,这个对象(A)应该属于他(B),为什么'const'? (也许你不想修改他,所以没关系) – Stargateur

你想用fill constructor。如果你不使用C++ 11,你需要指定向量中元素的默认值。count(g.node_count(), std::vector<bool>(16, true))

首先,我想问你是否知道vector<bool>是一种特殊类型的向量,由于优化,这在某些情况下会导致一些不同的行为。

如果你想使用它,你必须传递给构造函数vector<bool>(16, true)用16个真值填充它。