假设我有以下类(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)
构造函数。它用 t
的 n
个拷贝初始化 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/