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!
Asked
Active
Viewed 6.5k times
12
-
Check out http://stackoverflow.com/questions/258871/how-to-use-find-algorithm-with-a-vector-of-pointers-to-objects-in-c to see vectors in use. – eppdog Feb 01 '12 at 04:15
-
also http://stackoverflow.com/questions/817263/is-it-possible-to-create-a-vector-of-pointers – eppdog Feb 01 '12 at 04:16
1 Answers
30
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):
std::vector<int*> widgets{ new int(0), new int(1), new int(17) };
A smarter version of #3:
std::vector<std::unique_ptr<int>> stuff;
stuff.reserve(10);
for( int i = 0; i < 10; ++i )
stuff.emplace_back(new int(i));

Ben Voigt
- 277,958
- 43
- 419
- 720
-
-
`emplace_back` doesn't buy you anything with scalar types such as pointers. – fredoverflow Feb 01 '12 at 05:33
-
2@FredOverflow: `unique_ptr`'s constructor is explicit, so you either need to use `emplace_back` or `stuff.push_back(std::unique_ptr
(new int(i)));`. Between the two, `emplace_back` is much cleaner. – James McNellis Feb 01 '12 at 07:12 -
1