Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range-based for loop on vector that is a member variable

Tags:

c++

C++11

What's the code to iterate, using range-based for loop, over a std::vector that is a member of a class? I I've tried a few versions of the following:

struct Thingy {
  typedef std::vector<int> V;

  V::iterator begin() {
      return ids.begin();
  }

  V::iterator end() {
      return ids.end();
  }

  private:
      V ids;
};

// This give error in VS2013
auto t = new Thingy; // std::make_unique()
for (auto& i: t) {
    // ...
}

// ERROR: error C3312: no callable 'begin' function found for type 'Thingy *'
// ERROR: error C3312: no callable 'end' function found for type 'Thingy *'
like image 248
Dess Avatar asked Jun 13 '14 00:06

Dess


1 Answers

t is a Thingy *. You didn't define any functions for Thingy *, your functions are defined for Thingy.

So you have to write:

for (auto &i : *t)
like image 101
M.M Avatar answered Nov 14 '22 22:11

M.M