如何解决如何初始化本身具有非平凡构造函数的对象的stl向量?
| 假设我有以下课程:class MyInteger {
private:
int n_;
public:
MyInteger(int n) : n_(n) {};
// MORE STUFF
};
并假设此类没有默认的平凡构造函数MyInteger()
。由于某种原因,我必须总是提供一个int
进行初始化。然后假设在我的代码中的某个地方我需要一个vector<MyInteger>
。如何在此vector<>
中初始化每个MyInteger
组件?
我有两种情况(可能的解决方案是相同的,但无论如何我都会声明它们),这是函数内部的一个普通变量:
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
个副本初始化向量。例如:
#include <vector>
struct MyInt
{
int value;
MyInt (int value) : value (value) {}
};
struct MyStuff
{
std::vector<MyInt> values;
MyStuff () : values (10,MyInt (20))
{
}
};
逐一将元素推入向量。当值应该不同时,这可能很有用。例如:
#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) /* ... */})
{
}
};
当然,有一个选项可以提供默认的构造函数和/或使用非ѭ14other的东西。
希望能帮助到你。
,如果向量的元素不是默认可构造的,则某些事情您无法使用向量进行。您不能编写此代码(示例1):
vector<MyInteger> foo(10);
但是,您可以编写以下代码(示例2):
vector<MyInteger> foo(10,MyInteger(37));
(这只需要一个复制构造函数。)第二个参数是向量元素的初始化程序。
就您而言,您还可以编写:
vector<MyInteger> foo(10,37);
...因为MyInteger具有以\“ int \”作为参数的非显式构造函数。因此,编译器会将37强制转换为MyInteger(37)并给出与示例2相同的结果。
您可能想研究std :: vector上的文档。
,vector<MyInteger> foo(10,MyInteger(MY_INT_VALUE));
MyFunClass(int size,int myIntegerValue) : myVector(size,MyInteger(myIntegerValue)) {};
,除了可以很好地回答问题的所有答案之外,如果您的班级MyInteger不是可复制构造的,则可以使用此技巧:您可以创建vector< shared_ptr< MyInteger > >
,而不是创建vector< MyInteger>
。
,可以使用初始化列表,而无需引用基础对象。
#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;
}
输出:2 2 2
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。