c ++ 11 foreach语法和自定义迭代器 [英] c++11 foreach syntax and custom iterator
本文介绍了c ++ 11 foreach语法和自定义迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我为正在使用的容器的迭代器写一个STL容器。目前,在许多地方使用 c ++ 11 foreach语法来使用STL容器,例如: 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
};
如何让自动为自定义容器使用正确的迭代器,以便代码能够以下列方式调用:
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...
}
一般来说,为了确保自动对类使用正确的迭代器,需要什么?
In general what is required to ensure that auto uses the correct iterator for a class?
推荐答案
您有两种选择:
- 您提供名为
begin
的成员函数end
可以像C.begin()
和/ code>;
- 否则,您提供名为
begin
和end
可以使用参数相关查找,或在命名空间std
中找到,可以像begin(C)
和end(C)
。
- you provide member functions named
begin
andend
that can be called likeC.begin()
andC.end()
; - otherwise, you provide free functions named
begin
andend
that can be found using argument-dependent lookup, or in namespacestd
, and can be called likebegin(C)
andend(C)
.
这篇关于c ++ 11 foreach语法和自定义迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文