错误:从类型'std :: vector< bool> :: reference {aka std :: _ Bit_reference}'的右值对类型'bool&'的非常量引用进行了无效的初始化
为什么会出现错误:从类型为 std :: vector :: reference {aka std :: _ Bit_reference}的右值对 bool&类型的非常量引用进行无效的初始化?
Why do I get the error: invalid initialization of non-const reference of type ‘bool&’ from an rvalue of type ‘std::vector::reference {aka std::_Bit_reference}’?
vector<vector<bool>> vis;
bool& visited(int x, int y)
{
return vis[x][y]; //error
}
据我所知,vector中的operator []返回引用,因此它应该是一个左值,但不起作用。我应该怎么做才能使其正常工作?
As far as I know operator[] in vector returns reference, so it should be an lvalue, but it doesn't work. What should I do to make it work?
那是因为 std :: vector< bool>
不是它的样子。
That's because std::vector< bool >
is not what it looks like.
std有一个 specialization :: vector
类型为 bool
-已对空间进行了优化,并且每个元素都使用了一位。
There's a specialization for std::vector
with type bool
- it's space optimized and uses a single bit for each element.
如果需要此功能,可以尝试使用 uint8_t
或类似的方法。或者只返回 bool
,而不是 bool&
。
You can try to use uint8_t
or something like this, if you need this functionality. Or just return bool
, not bool&
.
operator []
返回的引用不是标准引用,而是代理类,这使这里的事情变得复杂。
The reference, returned by operator[]
is not a standard reference, but a proxy class, which complicates the things here.
这里有很多类似的问题:
There are a lot of similar questions about this here:
- 运算符| = on std :: vector< bool>
- 为什么vector< bool> :: reference不返回对bool的引用?
- 正在使用std :: vector< bool>的可以使用C ++中的对象,还是应该使用替代对象?
- operator |= on std::vector<bool>
- Why vector<bool>::reference doesn't return reference to bool?
- Is the use of std::vector<bool> objects in C++ acceptable, or should I use an alternative?
以及其他。了解有关 std :: vector<的更多信息。 bool>
专业化。
And others. Read more about std::vector< bool >
specialization.