[英]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.我有一个方法应该根据条件向前或向后迭代
map
。 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>
?也许使用
<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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.