c++11 foreach syntax and custom iterator(c++11 foreach 语法和自定义迭代器)
问题描述
我正在为一个用于代替 STL 容器的容器编写一个迭代器.目前 STL 容器在很多地方都使用 c++11 foreach 语法 例如:for(auto &x: C).我们需要更新代码以使用包装 STL 容器的自定义类:
I am writing an iterator for a container which is being used in place of a STL container. Currently the STL container is being used in many places with the c++11 foreach syntax eg: for(auto &x: C). We have needed to update the code to use a custom class that wraps the STL container:
template< typename Type>
class SomeSortedContainer{
std::vector<typename Type> m_data; //we wish to iterate over this
//container implementation code
};
class SomeSortedContainerIterator{
//iterator code
};
如何让 auto 为自定义容器使用正确的迭代器,以便能够通过以下方式调用代码?:
How do I get auto to use the correct iterator for the custom container so the code is able to be called in the following way?:
SomeSortedContainer C;
for(auto &x : C){
//do something with x...
}
通常需要什么来确保 auto 为类使用正确的迭代器?
In general what is required to ensure that auto uses the correct iterator for a class?
推荐答案
你有两个选择:
- 您提供名为
begin和end的成员函数,可以像C.begin()和C.end(); - 否则,您提供名为
begin和end的免费函数,可以使用参数相关查找或在命名空间std中找到它们,并且可以像begin(C)和end(C)一样调用.
- you provide member functions named
beginandendthat can be called likeC.begin()andC.end(); - otherwise, you provide free functions named
beginandendthat can be found using argument-dependent lookup, or in namespacestd, and can be called likebegin(C)andend(C).
这篇关于c++11 foreach 语法和自定义迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c++11 foreach 语法和自定义迭代器
基础教程推荐
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- c++ STL设置差异 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
