如何初始化指针的向量 [英] How to initialize a vector of pointers
本文介绍了如何初始化指针的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个C ++程序,我需要初始化一个指针的向量。我知道如何初始化一个向量,但如果有人可以告诉我如何初始化它作为一个向量填充指针,这将是巨大的!
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!
推荐答案
指针的零大小向量:
std::vector<int*> empty;
NULL指针向量:
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));
初始化指向新分配对象的指针向量(需要C ++ 11):
Initializing a vector of pointers to newly allocated objects (needs C++11):
std::vector<int*> widgets{ new int(0), new int(1), new int(17) };
#3的更聪明版本:
std::vector<std::unique_ptr<int>> stuff;
stuff.reserve(10);
for( int i = 0; i < 10; ++i )
stuff.emplace_back(new int(i));
这篇关于如何初始化指针的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文