繁体   English   中英

基于范围的for循环on vector是一个成员变量

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

C ++ 11

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

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)

如果可以,您应该使用“普通”对象:

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

或者使用std::unique_ptr然后取消引用指针:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM