I'm trying to assign a value to a vector, but I get this error. What is the issue about?
std::vector<bool> *boolVec = new std::vector<bool>(max, true);
boolVec[0] = false;
This code works:
boolVec->at(0) = false;
I'm trying to assign a value to a vector, but I get this error. What is the issue about?
std::vector<bool> *boolVec = new std::vector<bool>(max, true);
boolVec[0] = false;
This code works:
boolVec->at(0) = false;
try:
(*boolVec)[0] = false;
You have a pointer to a vector, so you have to dereference the pointer first.
You have a pointer to a vector std::vector<bool> *boolVec
This is not what you want. Just use a vector:
std::vector<bool> boolVec(max, true);
boolVec[0] = false;
The vector data will be stored on the heap.
If you truely need the pointer then you need to dereference it. You can use
(*boolVec)[0] = false;
or
boolVec->at(0) = false;
Note that using ->at(
will perform boundary checks and may be slower.
There are several ways to use the subscript operator
For example
( *boolVec )[0] = false;
or
boolVec[0][0] = false;
or
boolVec->operator []( 0 ) = false;
Here is a demonstrative program
#include <iostream>
#include <iomanip>
#include <vector>
int main( void )
{
std::vector<bool> *boolVec = new std::vector<bool>( 6, true );
boolVec[0][0] = false;
( *boolVec )[2] = false;
boolVec->operator []( 4 ) = false;
for ( bool b : *boolVec ) std::cout << std::boolalpha << b << ' ';
std::cout << std::endl;
delete boolVec;
}
false true false true false true
Consider also a possibility to define tha vector like
std::vector<bool> boolVec( 6, true );