错误:从类型'std :: vector< bool> :: reference {aka std :: _ Bit_reference}'的右值对类型'bool&'的非常量引用进行了无效的初始化 [英] error: invalid initialization of non-const reference of type ‘bool&’ from an rvalue of type ‘std::vector<bool>::reference {aka std::_Bit_reference}’

查看:152
本文介绍了错误:从类型'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:

  • 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.

这篇关于错误:从类型'std :: vector&lt; bool&gt; :: reference {aka std :: _ Bit_reference}'的右值对类型'bool&amp;'的非常量引用进行了无效的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆