如何调整 unique_ptr 向量的向量大小?

How to resize a vector of vector of unique_ptr?

如何在一行中正确调整 unique_ptr 个向量的大小而不 gcc 给出有关已删除函数的编译错误?

vector<vector<unique_ptr<A> >> a;
a.resize(..... )

更新: 这是我使用的代码,可以正常工作。

  int width, height;
  vector<vector<unique_ptr<A> >> a;
  a.resize(width);
  for (int i = 0; i < width; i++) {
      for (int j = 0; j < height; j++) {
          a.at(i).emplace_back(new A());

如果可能的话,我想像调整向量的向量大小一样一次性调整大小;

vector<vector<int>> intObj;
intObj.resize(width, vector<int>(height, int()));

但每当我尝试使用以下方法调整上述向量的大小时,我都会收到此错误;

a.resize(x, vector<unique_ptr<A>>(y, unique_ptr<A>()));

error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = A; _Dp = std::default_delete<A>]’

谢谢。

std::unique_ptr 不可复制使用 std::shared_ptr 以获得完整的容器支持。

问题是 vector<unique_ptr<A>> 是不可复制的类型,因为 unique_ptr<A>无法复制。 a.resize(x, vector<unique_ptr<A>>(y)) 使用了 vector<unique_ptr<A>> 的复制构造函数,而 a.resize(x, vector<unique_ptr<A>>(y, unique_ptr<A>())) 更糟糕,因为它使用了 unique_ptr<A>vector<unique_ptr<A>>.

的复制构造函数

两种解决方案:

  1. 使用大小为 x*y 的单个 vector<unique_ptr<A>>。这表示 a.resize(x*y) 将按预期工作。
  2. 或者,您需要对所有子向量使用循环。

循环示例:

a.resize(x);
for (auto& i : a) {
    i.resize(y);
}

编辑:如果您希望 unique_ptr<A>s 指向默认构造的 As 而不是 nullptr,那么您可以使用此代码:

a.resize(x);
for (auto& i : a) {
    i.reserve(y);
    for (int j = 0; y != j; ++j) {
        i.push_back(std::make_unique<A>());
    }
}

如果您保持当前的设计,则无法使用单个 resize 调用来执行您想要的操作。

编辑 2:如果您使用解决方案 1:

,这是默认构造 As 的单行代码
std::generate_n(std::back_inserter(a), x*y, []{ return std::make_unique<A>(); });