c++ - modifying vector returned by reference -


why size of below vector 0?

#include <iostream> #include<vector> using namespace std; class {      public:         vector<int> t;         const vector<int>& get(){             return t;         }         void print(){             cout<< " size "<<t.size();            // cout<<" \nelements %d "<<t[0];         } }; int main() {    cout << "hello world" << endl;     ob;    vector<int> temp = ob.get();    temp.clear();    temp.push_back(3);     temp.push_back(5);     ob.print();    return 0; } 

it's because nothing happened it. it's still empty.

you made copy of vector in temp, , modified copy, , not original class member. should use reference:

 vector<int> &temp = ob.get(); 

since returning reference get(), have assign reference. if don't, you're making copy of object.

edit: also, change get() return mutable reference, rather const reference.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -