Search code examples
c++c++11traversal

Custom container traversal with range-based for loop


In C++, some STL containers like vector, map, string can be traversed by for loops with colon in it.

for instance:

for(auto c:v)

When I'm writing a custom container, can I make it traversed that way like Java (which only need to implement Iterable)?


Solution

  • Yes, you need to implement some form of iterator and override std::begin(container) and std::end(container) (might work also if you container has begin and end methods).

    Internally the code is equivalent to something like the following (this is just to get the point across, the compiler can write it slightly differently, see here for more details).

    auto _end = end(v);
    for (auto _it = begin(v); _it != _end; ++_it) {  
        auto c = *_it;
        <the rest of loop code>
    }
    

    So if your iterator and overrides work as expected it will work for the for loop as well.