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

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

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_back,所以只调用 v.push_back 对我来说不起作用

如果有人能提供帮助就太好了。

你实际上从来没有将第二个输入写入任何东西。 Push_back 只被调用一次(在 v = createtable(v, insertedstr); 处调用的函数内),因此它只会包含一个值。您需要使用应该进入向量的第二个值实际调用 push_back。

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 的新向量。

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

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