c++ - 来自聚合类的对象 vector 中的 Push_back

标签 c++ vector struct aggregate push-back

我在使用 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() 只是为了有足够的空间放置元素。


vector::resize()

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.

vector::reserve()

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/

相关文章:

c++ - 模板元编程与经典名称重载相结合

python - 如何在调试python C扩展时设置断点并执行其他gdb命令

c++ - 向 vector 添加多个值

pointers - Golang 使用 New() 返回结构指针而不是直接创建一个

c++ - 如何将字符串传递给 GPU 并从内核中取回以显示它? (C++ OpenCL)

c++ - QFile不读取文件

python - 如何在Python中使用h.264引用软件提取运动向量

c++ - 将 vector 元素制作成字符串进行比较?

c++ - 为什么此 C++ 成员函数调用会因段错误而失败?

以 vector 作为成员的结构的 C++ 大小