c++11 foreach 语法和自定义迭代器

2022-01-10 00:00:00 iterator c++ c++11

我正在为一个用于代替 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?

推荐答案

你有两个选择:

  • 您提供名为 beginend 的成员函数,可以像 C.begin()C.end();
  • 否则,您提供名为 beginend 的免费函数,可以使用参数相关查找或在命名空间 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).

相关文章