Search code examples
c++iteratorreverse-iterator

reverse_iterator and iterator abstraction in a variable


I have a method that is supposed to iterate a map forward or backward, depending on a condition. Operations itself are independent on the direction, thus I would like to be able to do something like this:

std::map<int, int> some_map;
auto iter = some_condition ? some_map.begin() : some_map.rbegin();
for (; iter != some_condition ? some_map.end() : some_map.rend(); ++iter)
{
    //something to do with *iter
}

I know I should be able to do this with template function (right?), but it seems like a bit of an overkill.

Is there a way I could do it in one function, without template? Maybe with use of <algorithm>?


Solution

  • One way to do so would be to first factor out what you want to do with each element, say

    auto f = [](const std::pair<int, int> &p) { std::cout << p.first << std::endl; };
    

    Then you could branch on the direction:

    if(forward)
        std::for_each(std::begin(m), std::end(m), f);
    else
        std::for_each(std::rbegin(m), std::rend(m), f);