initialize vector of pointers (automatically)

早过忘川 提交于 2019-12-07 20:31:38

问题


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.



来源:https://stackoverflow.com/questions/10960508/initialize-vector-of-pointers-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!