Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a vector of pointers [closed]

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!

like image 815
Joshua Vaughan Avatar asked Feb 01 '12 04:02

Joshua Vaughan


People also ask

How do you initialize a vector of points in C++?

Another way to initialize a vector in C++ is to pass an array of elements to the vector class constructor. The array elements will be inserted into the vector in the same order, and the size of the vector will be adjusted automatically. You pass the array of elements to the vector at the time of initialization.

How do you declare a vector to a pointer?

You can store pointers in a vector just like you would anything else. Declare a vector of pointers like this: vector<MyClass*> vec; The important thing to remember is that a vector stores values without regard for what those values represent.

Does vector erase delete pointers?

Yes. vector::erase destroys the removed object, which involves calling its destructor.


1 Answers

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));
like image 101
Ben Voigt Avatar answered Sep 16 '22 21:09

Ben Voigt