c++ - 如何初始化本身具有非平凡构造函数的对象的 STL vector ?

标签 c++ constructor initialization initialization-list

假设我有以下类(class):

class MyInteger {
private:
  int n_;
public:
  MyInteger(int n) : n_(n) {};
  // MORE STUFF
};

假设这个类没有默认的平凡构造函数MyInteger() .我必须始终提供 int出于某种原因对其进行初始化。然后假设在我的代码中某处我需要一个 vector<MyInteger> .如何初始化每个 MyInteger vector<> 中的组件?

我有两种情况(可能解决方案是一样的,但我还是会说明它们),一个函数内部的普通变量:

int main(){
    vector<MyInteger> foo(10);  //how do I initialize each 
                                //MyInteger field of this vector? 
    doStuff(foo);
}

作为类中的数据:

class MyFunClass {
private:
   vector<MyInteger> myVector;

public:
   MyFunClass(int size, int myIntegerValue) : myVector(size) {}; 
   // what do I put here if I need the 
   // initialization to call MyInteger(myIntegerValue) for all 
   // components of myVector?
};

是否可以仅在初始化列表中执行此操作,还是必须在 MyFunClass(int, int) 构造函数中手动编写初始化?

这似乎非常基本,但我不知何故在我的书中错过了它,在网上找不到。

最佳答案

有很多方法可以到达那里。以下是其中的一些(排名不分先后)。

使用 vector(size_type n, const T& t) 构造函数。它用 tn 个拷贝初始化 vector 。例如:

#include <vector>

struct MyInt
{
    int value;
    MyInt (int value) : value (value) {}
};

struct MyStuff
{
    std::vector<MyInt> values;

    MyStuff () : values (10, MyInt (20))
    {
    }
};

将元素一个一个插入 vector 。当值应该不同时,这可能很有用。例如:

#include <vector>

struct MyInt
{
    int value;
    MyInt (int value) : value (value) {}
};

struct MyStuff
{
    std::vector<MyInt> values;

    MyStuff () : values ()
    {
        values.reserve (10); // Reserve memory not to allocate it 10 times...
        for (int i = 0; i < 10; ++i)
        {
            values.push_back (MyInt (i));
        }
    }
};

另一个选项是构造函数初始化列表,如果 C++0x 是一个选项:

#include <vector>

struct MyInt
{
    int value;
    MyInt (int value) : value (value) {}
};

struct MyStuff
{
    std::vector<MyInt> values;

    MyStuff () : values ({ MyInt (1), MyInt (2), MyInt (3) /* ... */})
    {
    }
};

当然,可以选择提供默认构造函数和/或使用 std::vector 以外的其他东西。

希望对你有帮助。

关于c++ - 如何初始化本身具有非平凡构造函数的对象的 STL vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6142830/

相关文章:

c++ - 我可以创建匹配枚举类型的类模板的部分模板特化吗?

c++ - 如何设置数据断点,以在 EAX 寄存器设置为特定值时中断

c++ - 如何比较c++列表中的两个连续元素

c++ - 静态成员和默认构造函数 C++

c - C语言数组中未初始化元素的取值

我可以在 C 中使用三元运算符为字符串赋值吗?

c++ - 在 Linux 上的 QT 应用程序中识别控件名称/ID

c++ - 当{}与new一起使用以创建std::array<T, n>时,将绕过T的默认构造函数

c++ - 在派生构造函数中调用基方法的坏习惯?

c - Malloc 数组,未初始化值的条件跳转