c ++ 11 foreach语法和自定义迭代器 [英] c++11 foreach syntax and custom iterator

查看:209
本文介绍了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 and end that can be called like C.begin() and C.end();
  • otherwise, you provide free functions named begin and end that can be found using argument-dependent lookup, or in namespace std, and can be called like begin(C) and end(C).

这篇关于c ++ 11 foreach语法和自定义迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆