简体   繁体   中英

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:

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. 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; 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 . If x > y , this leads to undefined behavior.

Assuming that x+1 is the row length, your vector is currently stored in column-major order (each inner vector represents one column). 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.

The C++ standard mandates std::vector<bool> to be a specialisation of std::vector . In particular, the data are packed tightly, 1 bit per element.

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.

As for an alternative, look at std::bitset .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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