Search code examples
c++vectorpush-back

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


The push_back method of the std::vector isn't putting the second console input in the v[1] slot, it keeps overwriting it in the v[0]

I tried to search for other answers to this but the code and answer is too complicated for me to follow, im trying to keep it simple (But i tried using pointers, just got a bunch of errors)

My Method:

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

            return vcreate;
}

Main:

                   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;

        }

Edit: I want to eventually write a menu for this so I want to have an infinite amount of push_backs, so just calling v.push_back in the main won't work for me

Would be great if someone could help.


Solution

  • You're creating a new vector in each call to createTable, not reusing an existing vector; you're not constantly inserting into v[0], you're constantly replacing v with a whole new vector that only has a single element. The second call to createTable should probably just be a direct call to v.push_back(insertedString);.

    Alternatively, remove the vcreate declaration and actually use the v passed into the function instead (which is still wasteful, because it's constantly copying and replacing vectors instead of pushing onto an existing one directly, but it would at least be logically correct).