在成员变量的vector上基于范围的for循环

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

本文关键字:范围 for 循环 变量 成员 vector 于范围      更新时间:2023-10-16

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 *'

tThingy *。你没有为Thingy *定义任何函数,你的函数是为Thingy定义的。

所以你必须写:

for (auto &i : *t)

如果可以的话,应该使用"normal"对象:

Thingy t;
for (auto& i: t) {
    // ...
}

或者使用std::unique_ptr,然后使用指针解引用:

auto t = std::make_unique<Thingy>();
for (auto& i: (*t)) {
    // ...
}