向量是成员变量的基于范围的for循环

Des*_*ess 4 c++

C ++ 11

使用基于范围的for循环在属于类成员的std :: vector上迭代的代码是什么?我尝试了以下几种版本:

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 *'
Run Code Online (Sandbox Code Playgroud)

M.M*_*M.M 5

t是一个Thingy *。您没有为定义任何功能Thingy *,而是为定义了功能Thingy

所以你必须写:

for (auto &i : *t)
Run Code Online (Sandbox Code Playgroud)