简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM