c++ - 作为成员变量的 vector 上的基于范围的 for 循环

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

最佳答案

t 是一个 Thingy *。您没有为 Thingy * 定义任何函数,您的函数是为 Thingy 定义的。

所以你必须写:

for (auto &i : *t)

关于c++ - 作为成员变量的 vector 上的基于范围的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24195881/

相关文章:

c++ - 使用类模板进行隐式转换

c++ - 帮助 Try Catch

c++ - 转换构造函数 : How do you explain a function given different arguments in c++

c++ - 多个模板匹配只检测一个匹配项

c++ - 命名空间 boost::detail 中没有名为 'dynamic_cast_tag' 的成员 (SALOME 7.3.0)

c++ - 如何在 SimGrid 中创建带有 vector 的进程?

c++ - CMake CEGUI/GTK2 配置错误

c++ - 返回字符串的静态方法

python - 为什么不能使用 std::ref 将对象传递到 Boost.Python 模块中?

c++ - CATCH_CONFIG_MAIN 的 gtest 等价物是什么?