【问题标题】:How to add elements to vector<MyType> when MyType has no default constructor and no copy constructor?当 MyType 没有默认构造函数且没有复制构造函数时,如何向 vector<MyType> 添加元素?
【发布时间】:2014-10-15 22:58:18
【问题描述】:

简而言之,当该类未定义复制构造函数且没有默认构造函数时,我想将元素添加到类元素向量中。这是一个最小的示例(感谢 juanchopanza 修复了我的示例):

class MyType {
 public:
  MyType(int height, int width);
  MyType() = delete;
}

#include <vector>
int some_function() {
  // Define the vector.
  std::vector<MyType> array;
  // Define an element.
  MyType element(1,2);
  // Now, how do I add an element to the vector?
  //array.resize(1); // NO DEFAULT CONSTRUCTOR SO THIS WON'T WORK.
  //array.push_back(element); // NO COPY CONSTRUCTOR SO THIS WON'T WORK.
}

我最好的猜测是,我不能将向量与类一起使用,除非它具有复制构造函数或默认构造函数。寻找验证或启发。

我检查了this、this、this 和this,但没有一个能解决我的问题。

【问题讨论】:

  • 你有没有不小心把MyType复制成可构造的?

标签: c++ vector


【解决方案1】:

只要类型是可移动构造的,你就可以用emplace_back就地构造它:

array.emplace_back(1,2);

但请注意,您的示例 确实 有一个复制构造函数,所以这也可以工作,与您的说法相反:

MyType element(1,2);
array.push_back(element);

这是您的示例的简化版:

struct MyType 
{
  MyType(int height, int width) {}
  MyType() = delete;
};

#include <vector>

int main() 
{
  std::vector<MyType> array;
  array.emplace_back(1,2);
}

【讨论】:

  • 正确!谢谢你。只要 stackoverflow 允许,我就会接受。
  • 所以,在 c++11 之前,这是不可能的?!
  • @Ammar 实际上,您的示例 确实 有一个复制构造函数。没有一个,我的例子就行不通。
猜你喜欢
  • 2023-03-20
  • 1970-01-01
  • 2021-09-02
  • 2016-07-18
  • 2011-07-15
  • 1970-01-01
  • 2015-07-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多