如何初始化自身具有非平凡构造函数的对象的stl向量?

Raf*_*ini 31 c++ constructor initialization initialization-list

假设我有以下课程:

class MyInteger {
private:
  int n_;
public:
  MyInteger(int n) : n_(n) {};
  // MORE STUFF
};
Run Code Online (Sandbox Code Playgroud)

并且假设这个类没有默认的普通构造函数MyInteger().int出于某种原因,我必须始终提供初始化它.然后假设在我的代码中的某个地方我需要一个vector<MyInteger>.如何MyInteger在此初始化每个组件vector<>

我有两种情况(可能解决方案是相同的,但无论如何我都会说明),一个函数内的正常变量:

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

并作为班级中的数据:

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?
};
Run Code Online (Sandbox Code Playgroud)

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

这看起来非常基本,但我在书中错过了它,在网上找不到.

小智 31

有很多方法可以实现这一目标.以下是其中一些(没有特定的存在顺序).

使用vector(size_type n, const T& t)构造函数.它用n副本初始化向量t.例如:

#include <vector>

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

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

    MyStuff () : values (10, MyInt (20))
    {
    }
};
Run Code Online (Sandbox Code Playgroud)

将元素逐个推入向量.当值应该不同时,这可能很有用.例如:

#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));
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

另一个选项是构造函数初始化列表,如果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) /* ... */})
    {
    }
};
Run Code Online (Sandbox Code Playgroud)

当然,有一个选项可以提供默认构造函数和/或使用其他东西std::vector.

希望能帮助到你.


Nem*_*emo 11

如果向量的元素不是默认构造的,那么有些事情你无法用向量做.你不能写这个(例1):

vector<MyInteger> foo(10);
Run Code Online (Sandbox Code Playgroud)

但是,你可以这样写(例2):

vector<MyInteger> foo(10, MyInteger(37));
Run Code Online (Sandbox Code Playgroud)

(这只需要一个复制构造函数.)第二个参数是向量元素的初始值设定项.

在你的情况下,你也可以写:

vector<MyInteger> foo(10, 37);
Run Code Online (Sandbox Code Playgroud)

...因为MyInteger有一个非显式构造函数,以"int"作为参数.因此编译器会将37转换为MyInteger(37),并给出与示例2相同的结果.

您可能想要研究std :: vector上文档.


mby*_*kov 6

vector<MyInteger> foo(10, MyInteger(MY_INT_VALUE));

MyFunClass(int size, int myIntegerValue) : myVector(size, MyInteger(myIntegerValue)) {}; 
Run Code Online (Sandbox Code Playgroud)


BЈо*_*вић 6

除了能够很好地回答问题的所有答案之外,如果您的类MyInteger不是可复制构造的,您可以使用这个技巧:而不是创建vector< MyInteger>,您可以创建vector< shared_ptr< MyInteger > >