【问题标题】:Is it possible to initialize an array of values for a vector during copy construction using the initializer list?是否可以在复制构造期间使用初始化器列表初始化向量的值数组?
【发布时间】:2017-04-16 07:16:36
【问题描述】:

我想使用复制构造函数的初始化列表而不是在构造函数的主体中调用 pushElements 将值从 1 到 9 添加到我的向量中。这怎么可能?

Hane::Hane(int val, bool veri){

}

Hane::Hane():m_myvalue(0), m_myveri(false) {
    pushElements();
}
Cell::~Cell() {}

void Cell::pushElements() {

     m_vector = { 1,2,3,4,5,6,7,8,9 };

}

来自 Hane.h

 private:

std::vector<int> m_vector;

【问题讨论】:

  • 你的目标向量在哪里?
  • 我已经添加了我在 .h 文件中声明向量的代码
  • 为什么要在 pushElements() 函数中再次声明?
  • 我是 C++ 新手,我不知道如何将值推入其中。我做了那个方法,但我想完全摆脱它,而是在复制构造期间将值赋给向量
  • @RamzahRehman 我修复了重新声明

标签: c++ stl copy-constructor stdvector


【解决方案1】:

只需使用constructor that takes an initializer list(8):

struct myclass
{
    std::vector<int> m_vector;
    myclass() : m_vector{ 1,2,3,4,5,6,7,8,9 } {}
};

Live demo.

...或者更简单,直接初始化向量:

struct myclass
{
    std::vector<int> m_vector{ 1,2,3,4,5,6,7,8,9 };
};

Live demo.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    相关资源
    最近更新 更多