在成员变量的vector上基于范围的for循环
Range-based for loop on vector that is a member variable
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)
如果可以的话,应该使用"normal"对象:
Thingy t;
for (auto& i: t) {
// ...
}
或者使用std::unique_ptr
,然后使用对指针解引用:
auto t = std::make_unique<Thingy>();
for (auto& i: (*t)) {
// ...
}
相关文章:
- 在基于范围的for循环中使用结构化绑定声明
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 基于范围的 for 循环unordered_map和引用
- C++基于范围的 for 循环和元素副本
- 实现基于链表的堆栈的基于范围的 for 循环
- 在基于范围的 for 循环期间插入 std::list 的后面
- 基于范围的 for 循环range_declaration中各种说明符之间的性能差异
- 避免在基于反向范围的for循环实现中悬挂参考
- C++ - 使用基于范围的 for 循环将字符值分配给向量中的字符串不会分配值
- 转到基于范围的 for 循环中的下一个迭代器
- 使用基于数组和范围的 For 循环替换一些基本代码行
- C++:返回一个基于范围 for 循环迭代器,其中包含继承对象
- 布尔值向量的基于范围 for 循环
- 在 c++ 中基于范围的 for 循环中使用引用作为控制变量
- C++11 基于范围的 for 循环,用于 std::list
- 堆分配数组的基于范围的 for 循环
- 关于在向量向量上使用基于范围的 for 循环
- 如何使用基于范围的for循环迭代Rapidjson文档(它本身就是一个JSON数组)
- 使用基于范围的for循环取消对矢量指针的引用