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
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)
.
相关文章