3

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

4
  • And inside <algorithm>, you have templates. Commented Sep 9, 2016 at 8:17
  • @LogicStuff I am aware of that, but I don't have to write them - just a lambda, which I would consider cleaner (readability wise) in this case Commented Sep 9, 2016 at 8:19
  • You can see this and read the example, they use iterator. Commented Sep 9, 2016 at 8:20
  • @AlejandroCortes ?? Commented Sep 9, 2016 at 8:20

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.