Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a vector of unique_ptr with null pointers?

I need to initialize a vector<unique<TNode>> with nullptrs. The method in this post is too complicated. My situation is special since I only need to initialize it as nullptr. How can I achieve it?

I know I can use a for-loop to push_back a nullptr each time. Is there an elegant way?

BTW, make_unqiue does not work on my compiler.

#include <iostream>
#include <memory>
#include <vector>

using namespace std;

struct TNode {
    //char ch;
    bool isWord;
    vector<unique_ptr<TNode> > children;
    TNode(): isWord(false), children(26,nullptr) {}
};

int main()
{
    TNode rt;
    return 0;
}
like image 819
user3813057 Avatar asked Feb 22 '18 01:02

user3813057


2 Answers

std::vector<std::unique_ptr<int>> v (10);

It will create a vector of 10 unique_ptr objects, all of which are default initialized (not making any copies). The default initialization for unique_ptr points to nothing.

Note this is quite different from this:

std::vector<std::unique_ptr<int>> v (10, nullptr);

Which tries to initialize the vector with 10 copies of a unique_ptr that is initialized to nullptr, which cannot be done since unique_ptr can't be copied.

like image 176
AdvSphere Avatar answered Oct 15 '22 03:10

AdvSphere


You can simply write:

struct TNode {

    Tnode(unsigned required_children) :
        children(required_children) {}
...

     vector<unique_ptr<TNode> > children;

From the page on the std::unique_ptr constructor you will see that this will:

Construct a std::unique_ptr that owns nothing.

to the number that you pass in in the constructor of your structure. So you can do:

TNode rt(number_I_want);

And you will have number_I_want unique pointers in your vector. They will not necessarily hold nullptr, but they know they hold nothing which is all you should care about.

like image 30
Fantastic Mr Fox Avatar answered Oct 15 '22 03:10

Fantastic Mr Fox