user3813057
user3813057

Reputation: 911

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;
}

Upvotes: 7

Views: 8710

Answers (3)

Dat
Dat

Reputation: 5813

Another solution is to use std::array so you could specify the size easier.

#include <array>

class TNode {
 private:
  struct TNode {
    bool end_of_word = false;
    std::array<std::unique_ptr<TNode>, 26> links;
  };

  TNode root;
  // The rest of your Trie implementation
  ...

Upvotes: 0

AdvSphere
AdvSphere

Reputation: 986

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.

Upvotes: 16

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

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.

Upvotes: 1

Related Questions