c++ - Method returning container for use in range-based for loop -


i have class contains standard container want return in method, (just example):

class intarray { public:     intarray(const vector<int>& vals) : vals(vals) {}      const vector<int>& getvalues() const { return vals; }     vector<int>& getvalues() { return vals; }  private:     vector<int> vals; }; 

i returned vector reference avoid making copy of (i rather not want rely on rvo). don't want using outputiterators, because want keep short c++11 range-based loops so:

for (int val : arr.getvalues()) {     // } 

but want change type of member variable list<int>, have change method's return type, too, might lead incompatibilities. don't want implement begin() , end() methods because there might more 1 such container per class.

what preferred way of doing this?

you create typedef , refer in function signatures:

class intarray { public:     typedef std::vector<int> vec;      intarray(const vec& vals) : vals(vals) {}      const vec& getvalues() const { return vals; }     vec& getvalues() { return vals; }  private:     vec vals; }; 

now if want change storage type, change typedef:

typedef std::list<int> vec; 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -