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 语法和自定义迭代器
				
        
 
            
        - STL 中有 dereference_iterator 吗? 2022-01-01
 - 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
 - 近似搜索的工作原理 2021-01-01
 - 使用/clr 时出现 LNK2022 错误 2022-01-01
 - 静态初始化顺序失败 2022-01-01
 - C++ 协变模板 2021-01-01
 - 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
 - 从python回调到c++的选项 2022-11-16
 - Stroustrup 的 Simple_window.h 2022-01-01
 - 如何对自定义类的向量使用std::find()? 2022-11-07
 
						
						
						
						
						
				
				
				
				