c++ - 没有默认构造函数的类 vector

标签 c++ c++11 vector

考虑以下类:

Class A
{
    public:
       A() = delete;
       A(const int &x)
       :x(x)
       {}
    private:
       int x;
};

如何创建 std::vector<A>并为构造函数 A::A(const int&) 提供一个参数?

最佳答案

How can I create a std::vector of type A and give an argument to A's constructor?

std::vector<A> v1(10, 42);  // 10 elements each with value 42
std::vector<A> v2{1,2,3,4}; // 4 elements with different values

How would I add 3 to the vector?

v.emplace_back(3);          // works with any suitable constructor
v.push_back(3);             // requires a non-explicit constructor

缺少默认构造函数仅意味着您无法执行需要的操作,例如

vector<A> v(10);
v.resize(20);

两者都将默认构造的元素插入 vector 中。

关于c++ - 没有默认构造函数的类 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29920394/

相关文章:

c++ - 在 C++ 和 C 中共享一个结构?

c++ - 从 exe 生成 Shellcode?

C++ 为什么要隐式调用转换器构造函数?

c++ - 如何在 C++ 中散列

c++ - 为什么这个 c++ 代码不能在 g++ 4.8.2 中编译

c++ - 建议的堆栈分配最大大小

c++ - 如何使用模板处理多类型变量?

python - numpy中不同形状数组之间的乘法

c++ - vector C++ 中的字节

c++ - 解释器的良好优化