如何用空指针初始化 unique_ptr 的向量?

How to initialize a vector of unique_ptr with null pointers?

我需要用 nullptr 初始化一个 vector<unique<TNode>>this post中的方法太复杂了。我的情况比较特殊,只需要初始化为nullptr。我怎样才能实现它?

我知道我每次都可以使用 for 循环 push_back nullptr。有什么优雅的方法吗?

顺便说一句,make_unqiue 不适用于我的编译器。

#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);

它将创建一个包含 10 个 unique_ptr 对象的向量,所有这些对象都是默认初始化的(不制作任何副本)。 unique_ptr 的默认初始化指向任何内容。

请注意,这与此完全不同:

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

它尝试用初始化为 nullptrunique_ptr 的 10 个副本来初始化向量,这无法完成,因为 unique_ptr 无法复制。

你可以简单地写:

struct TNode {

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

     vector<unique_ptr<TNode> > children;

std::unique_ptr constructor 上的页面您会看到这将:

Construct a std::unique_ptr that owns nothing.

到您在结构的构造函数中传入的数字。所以你可以这样做:

TNode rt(number_I_want);

你的向量中会有 number_I_want 个独特的指针。他们不一定持有 nullptr,但他们知道他们没有持有任何你应该关心的东西。

另一个解决方案是使用 std::array 这样您就可以更轻松地指定大小。

#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
  ...