Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 250
WAifT39 Avatar asked May 03 '20 07:05

WAifT39


1 Answers

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.

like image 51
Sorin Avatar answered Nov 11 '22 20:11

Sorin