简体   繁体   English

分配错误的C ++向量错误:“迭代器不可取消引用”

[英]C++ Vector of bools error: “iterator not dereferencable” when assigning values

I'm writing some code to create a dynamic 2d Vector of Booleans in C++ and then trying to assign values to it but i'm receiving the error: 我正在编写一些代码以在C ++中创建一个动态的布尔2d矢量,然后尝试为其分配值,但是我收到了错误:

Expression:vector<bool> iterator not dereferencable

my vector definition is as follows: 我的向量定义如下:

vector<vector<bool> > sol((x+1), vector<bool>(y+1));

I then try and assign values to the first row as follows: 然后,我尝试将值分配给第一行,如下所示:

for (int i = 0; i <= x; i++) {
    sol[0][i] = true;
}

But I receive the error described above. 但是我收到上述错误。 x and y are defined previously and are integers. x和y之前已定义,并且是整数。 I have found multiple questions regarding iterators not being dereferencable but haven't been able to apply the fixes for those to my own problem so any insight is welcome, thanks in advance for your time! 我发现了多个关于迭代器不是不可取的问题,但尚未针对我自己的问题应用这些修复程序,因此欢迎您提供任何见解,在此先感谢您的宝贵时间!

Your code is mostly correct. 您的代码大部分是正确的。 Despite what the other answer says, you can assign into a vector<bool> with vec[i]=true; 不管其他答案怎么说,您都可以将vec[i]=true;分配给vector<bool> vec[i]=true; like you're doing. 就像你在做。

The issue with your code, however, is that x+1 is the size of the outer dimension of the 2d vector, but you're using it to iterate over the inner dimension which is sized y+1 . 但是,代码的问题在于x+1是2d向量外部尺寸的大小,但是您正在使用它来遍历内部尺寸y+1 If x > y , this leads to undefined behavior. 如果x > y ,则导致未定义的行为。

Assuming that x+1 is the row length, your vector is currently stored in column-major order (each inner vector represents one column). 假设x+1是行长,则向量当前按列优先顺序存储(每个内部向量代表一列)。 If you want row-major order instead (which is more commonly used), replace x+1 and y+1 in the vector initialization and then your for loop will work. 如果要改为行优先的顺序(这是更常用的),请在向量初始化中替换x+1y+1 ,然后for循环将起作用。

The C++ standard mandates std::vector<bool> to be a specialisation of std::vector . C ++标准要求std::vector<bool>std::vector的特殊化。 In particular, the data are packed tightly, 1 bit per element. 特别是,数据被紧密打包,每个元素1位。

It is therefore not possible to dereference an iterator over a vector of bool s: the standard does not specify a size for the bool type. 因此,不可能在bool的向量上取消引用迭代器:标准未指定bool类型的大小。

As for an alternative, look at std::bitset . 至于替代方法,请查看std::bitset

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM