I need to initialize a vector<unique<TNode>>
with nullptr
s. 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;
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With