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


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

i tried search other answers code , answer complicated me follow, im trying keep simple (but tried using pointers, got 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);                  (int = 0; <=v.size(); i++) {                     cout << v[i] << endl;         }         cin >> insertedstr;    v = createtable(v, insertedstr);             (int = 0; <= v.size(); i++) {       cout << v[i] << endl;     }         return 0;          } 

edit: want write menu want have infinite amount of push_backs, calling v.push_back in main won't work me

would great if help.

you're creating new vector in each call createtable, not reusing existing vector; you're not inserting v[0], you're replacing v whole new vector has single element. second call createtable should direct call v.push_back(insertedstring);.

alternatively, remove vcreate declaration , use v passed function instead (which still wasteful, because it's copying , replacing vectors instead of pushing onto existing 1 directly, @ least logically correct).


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -