C++ 如何初始化本身具有非平凡构造函数的对象的 stl 向量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6142830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I initialize a stl vector of objects who themselves have non-trivial constructors?
提问by Rafael S. Calsaverini
suppose I have the following class:
假设我有以下课程:
class MyInteger {
private:
int n_;
public:
MyInteger(int n) : n_(n) {};
// MORE STUFF
};
And suppose this class don't have a default trivial constructor MyInteger()
. I must always supply an int
to initialize it for some reason. And then suppose that somewhere in my code I need a vector<MyInteger>
. How do I initialize each MyInteger
component in this vector<>
?
并且假设这个类没有默认的平凡构造函数MyInteger()
。int
由于某种原因,我必须始终提供一个来初始化它。然后假设在我的代码中的某个地方我需要一个vector<MyInteger>
. 我如何初始化MyInteger
这个中的每个组件vector<>
?
I have two situations (probably the solution is the same, but I'll state them anyway), a normal variable inside a function:
我有两种情况(可能解决方案是相同的,但无论如何我都会说明它们),函数内的一个普通变量:
int main(){
vector<MyInteger> foo(10); //how do I initialize each
//MyInteger field of this vector?
doStuff(foo);
}
and as data in a class:
并作为类中的数据:
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?
};
Is it possible to do it just in the initialization list or must I write the initialization by hand in the MyFunClass(int, int) constructor?
是否可以仅在初始化列表中执行此操作,还是必须在 MyFunClass(int, int) 构造函数中手动编写初始化?
This seems so very basic, and yet I somehow missed it inmy book and can't find in the web.
这看起来非常基本,但我不知何故在我的书中错过了它并且在网上找不到。
采纳答案by Rafael S. Calsaverini
There are many ways to get there. Here are some of them (in no particular order of presence).
有很多方法可以到达那里。以下是其中一些(没有特定的出现顺序)。
Use vector(size_type n, const T& t)
constructor. It initializes vector with n
copies of t
. For example:
使用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))
{
}
};
Push elements into vector one by one. This might be useful when values should be different. For example:
将元素一一推入向量中。当值应该不同时,这可能很有用。例如:
#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));
}
}
};
Another option is constructor initialization list, if C++0x is an option:
另一个选项是构造函数初始化列表,如果 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) /* ... */})
{
}
};
Of course, there is an option to provide default constructor and/or use something other than std::vector
.
当然,可以选择提供默认构造函数和/或使用std::vector
.
Hope it helps.
希望能帮助到你。
回答by Nemo
If the elements of the vector are not default-constructible, then there are certain things you cannot do with the vector. You cannot write this (example 1):
如果向量的元素不是默认构造的,那么有些事情你不能用向量做。您不能这样写(示例 1):
vector<MyInteger> foo(10);
You can, however, write this (example 2):
但是,您可以这样写(示例 2):
vector<MyInteger> foo(10, MyInteger(37));
(This only requires a copy constructor.) The second argument is an initializer for the elements of the vector.
(这只需要一个复制构造函数。)第二个参数是向量元素的初始值设定项。
In your case, you could also write:
在你的情况下,你也可以写:
vector<MyInteger> foo(10, 37);
...since MyInteger has a non-explicit constructor taking "int" as argument. So the compiler will cast 37 to MyInteger(37) and give the same result as example 2.
...因为 MyInteger 有一个以“int”为参数的非显式构造函数。因此编译器会将 37 转换为 MyInteger(37) 并给出与示例 2 相同的结果。
You might want to study the documentation on std::vector.
您可能想研究有关 std::vector的文档。
回答by mbykov
vector<MyInteger> foo(10, MyInteger(MY_INT_VALUE));
MyFunClass(int size, int myIntegerValue) : myVector(size, MyInteger(myIntegerValue)) {};
回答by B?ови?
Besides all answers which answered the question very well, in a case that your class MyInteger is not copy-constructible, you could use this trick : instead of creating vector< MyInteger>
, you could create vector< shared_ptr< MyInteger > >
除了所有答案都很好地回答了这个问题,如果你的类 MyInteger 不是可复制构造的,你可以使用这个技巧:而不是创建vector< MyInteger>
,你可以创建vector< shared_ptr< MyInteger > >
回答by edW
Initialization lists can be used without reference to the underlying objects.
可以在不参考底层对象的情况下使用初始化列表。
#include <string>
#include <vector>
using namespace std;
class Test
{
public:
struct NumStr
{
int num;
string str;
};
Test(vector<int> v1,vector<NumStr> v2) : _v1(v1),_v2(v2) {}
vector<int> _v1;
vector<NumStr> _v2;
};
int main()
{
Test t={ {1,2,3}, {{1,"one"}, {2,"two"}, {3,"three"}} };
cout << t._v1[1] << " " << t._v2[1].num << " " << t._v2[1].str << endl;
return 0;
}
output: 2 2 two
输出:2 2 两个