矢量函数"push_back"不断将值重写到内存中的同一插槽

vector function "push_back" keeps rewriting the value to the same slot in memory

本文关键字:写到内存 插槽 push 函数 back      更新时间:2023-10-16

std::vector的push_back方法没有将第二个控制台输入放在v[1]插槽中,它一直覆盖它在v[0]

我试图寻找其他答案,但代码和答案对我来说太复杂了,我试图保持简单(但我尝试使用指针,只是得到了一堆错误)

我的方法:

      vector<string> createtable(std::vector<std::string> v, std::string insertedstr) {
        std::vector<std::string> vcreate;
        vcreate.push_back(insertedstr + " ");
            return vcreate;
}
主:

                   int main()
                {
                    int option;
                    std::string insertedstr;
                    std::vector<std::string> v;
                cin >> insertedstr;
                   v = createtable(v, insertedstr);
                for (int i = 0; i <=v.size(); i++) {
                    cout << v[i] << endl;
        }
        cin >> insertedstr;
   v = createtable(v, insertedstr);
            for (int i = 0; i <= v.size(); i++) {

    cout << v[i] << endl;
    }
        return 0;
        }

编辑:我想最终为这个写一个菜单,所以我想有一个无限数量的push_backs,所以只是在主程序中调用v.p ash_back对我来说是行不通的

如果有人能帮忙就太好了。

在每次调用createTable时创建一个新的vector,而不是重用现有的vector;你不是不断地插入v[0],你不断地用一个只有一个元素的全新向量替换v。对createTable的第二个调用可能只是对v.push_back(insertedString);的直接调用。

或者,删除vcreate声明并实际使用传递到函数中的v(这仍然是浪费,因为它不断地复制和替换vector s,而不是直接推送到现有的,但它至少在逻辑上是正确的)。

您实际上从未将第二个输入写入任何内容。Push_back只被调用一次(在v = createtable(v, insertedstr);调用的函数中),所以它只包含一个值。您需要实际调用push_back,并使用第二个应该进入vector的值。

vector<string> createtable(std::vector<std::string> v, std::string insertedstr) {
    //std::vector<std::string> vcreate; // Not required
    v.push_back(insertedstr + " ");
    return v;
}

这个函数有问题。您每次都创建新的矢量vcreate,而不是使用传递的矢量v。所以每次都会有一个大小为1的新向量