Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize vector of pointers (automatically)

I encountered a compilation error when trying to initialize a vector of pointers to NULL by way of the std::vector constructor. I simplify the instruction to keep it simple:

vector<int*> v (100,NULL)

I guess it has something to do with an incompatibility between const T& value= T() (the parameter of the constructor) and the very value NULL, but I would appreciate some further explanation.

Thank you

like image 357
Lazaro Arribas Avatar asked Jun 19 '26 14:06

Lazaro Arribas


2 Answers

If you have the relevant C++11 support, you could use nullptr:

std::vector<int*> v(100, nullptr);

However, in your particular case, there is no need to specify a default value, so the following would suffice:

std::vector<int*> v(100);
like image 108
juanchopanza Avatar answered Jun 21 '26 03:06

juanchopanza


NULL is likely defined as 0, so you end up with

vector<int*> v(100,0);

which tries to build a vector of ints, not of int*s.

Just skip the NULL, as that is default for pointers anyway, or cast it to the correct pointer type (int*)NULL.

like image 20
Bo Persson Avatar answered Jun 21 '26 03:06

Bo Persson