C++ 如何初始化指针向量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9090680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to initialize a vector of pointers
提问by Joshua Vaughan
I am working on a C++ program, and I need to initialize a vector of pointers. I know how to initialize a vector, but if someone could show me how to initialize it as a vector filled with pointers that would be great!
我正在开发一个 C++ 程序,我需要初始化一个指针向量。我知道如何初始化一个向量,但是如果有人能告诉我如何将它初始化为一个充满指针的向量,那就太好了!
回答by Ben Voigt
A zero-size vector of pointers:
一个零大小的指针向量:
std::vector<int*> empty;
A vector of NULL pointers:
空指针向量:
std::vector<int*> nulled(10);
A vector of pointers to newly allocated objects (not really initialization though):
指向新分配对象的指针向量(虽然不是真正的初始化):
std::vector<int*> stuff;
stuff.reserve(10);
for( int i = 0; i < 10; ++i )
stuff.push_back(new int(i));
Initializing a vector of pointers to newly allocated objects (needs C++11):
初始化指向新分配对象的指针向量(需要 C++11):
std::vector<int*> widgets{ new int(0), new int(1), new int(17) };
A smarter version of #3:
#3 的更智能版本:
std::vector<std::unique_ptr<int>> stuff;
stuff.reserve(10);
for( int i = 0; i < 10; ++i )
stuff.emplace_back(new int(i));