T.Poe
T.Poe

Reputation: 2079

Initializing a vector of pointers to vector

I have this vector of pointers to vector:

std::vector<std::shared_ptr<std::vector<int>>> vec;

I want to initialize the first pointer to be a pointer to an empty vector. I tried this:

vec.push_back(nullptr);

Then I want to push_back some value to the vector where the nullptr points. I did this:

vec[0]->push_back(x);

Which I know is wrong, it ends up in segfault. I tried to do something with make_shared() instead of nullptr, but I still can't figure out how to achieve what I mentioned. Could anyone help me fix this example?

Upvotes: 1

Views: 527

Answers (1)

If you want vec to contain one valid shared pointer to a vector, it's as simple as

vec.emplace_back(std::make_shared<std::vector<int>>());

Now there's pointer there, and it points at valid object. Making your subsequent sub-scripting and dereference valid themselves.

Just be sure you don't do it second. If you insert a nullptr first, and then a valid pointer, then it will be vec[1] that points at an object, not vec[0]. Your original attempt places an empty shared pointer at the start of the vector. And it doesn't go anywhere if you insert more elements after it.

Upvotes: 7

Related Questions