initialize vector of pointers (automatically)

2019-05-28 16:42发布

问题:

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

回答1:

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);


回答2:

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.