我在使用 vector 时遇到了一点问题。据我了解,push_back()
将复制参数并将拷贝插入 vector 中。
struct BridgeData
{
string name;
string type;
};
对于像我这样的简单聚合类,应该通过复制两个字段来制作对象的拷贝。
for ( int i = 0; i<len; i++)
{
BridgeData data = {grp.get(1+i).asString().c_str()};
v.push_back(data);
cout << v[i].name << endl;
}
与 vector<BridgeData> &v
.
当我打印 data.name
时,我得到了我在花括号列表中使用的值,但是当我打印 v[i].name
时,该字段似乎是空的...此类聚合类的默认拷贝“构造函数”是否默认初始化所有字段?
编辑:
如果这还不够,这里还有更多代码。我有一个包含数据成员的类 vector<BridgeData> yarpGroups
.然后我将它作为引用传递到同一类的方法主体中:readBridgeDataVector(bGeneral,"yarpgroups",yarpGroups,numberOfYarpGroups);
.
请忽略其他参数,因为它们无关紧要(我确信)。
较早的片段来自此函数:
void readBridgeDataVector(Bottle &rf, string name, vector<BridgeData> &v, int len)
{
v.resize(len);
if(rf.check(name.c_str()))
{
Bottle &grp = rf.findGroup(name.c_str());
for ( int i = 0; i<len; i++)
{
BridgeData data = {grp.get(1+i).asString().c_str(),"float"};
v.push_back(data);
cout << v[0].name << endl;
}
}
else
{
cout << "Could not find parameters for " << name << ". "
<< "Setting everything to null by default" << endl;
}
}
最佳答案
您已将 vector 的大小调整为 len。
这会使用默认构造函数在 vector 中创建 len 对象。
因此,当您pushback()
另一个对象时,它就位 len+1。
单元格 0 中的对象实际上是默认构造的对象之一。
我想你想做的是使用 reserve() 只是为了有足够的空间放置元素。
If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized.
If n is greater than the current vector capacity, the function causes the container to reallocate its storage increasing its capacity to n (or greater).
关于c++ - 来自聚合类的对象 vector 中的 Push_back,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16709261/