reverse_iterator 和变量中的迭代器抽象
reverse_iterator and iterator abstraction in a variable
我有一个方法可以根据条件向前或向后迭代 map
。操作本身与方向无关,因此我希望能够做这样的事情:
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
}
我知道我应该可以使用模板函数来做到这一点(对吗?),但这似乎有点矫枉过正。
有没有一种方法可以在没有模板的情况下在一个函数中完成?也许使用 <algorithm>
?
这样做的一种方法是首先考虑要对每个元素执行的操作,比如
auto f = [](const std::pair<int, int> &p) { std::cout << p.first << std::endl; };
那么你可以在方向上分支:
if(forward)
std::for_each(std::begin(m), std::end(m), f);
else
std::for_each(std::rbegin(m), std::rend(m), f);
我有一个方法可以根据条件向前或向后迭代 map
。操作本身与方向无关,因此我希望能够做这样的事情:
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
}
我知道我应该可以使用模板函数来做到这一点(对吗?),但这似乎有点矫枉过正。
有没有一种方法可以在没有模板的情况下在一个函数中完成?也许使用 <algorithm>
?
这样做的一种方法是首先考虑要对每个元素执行的操作,比如
auto f = [](const std::pair<int, int> &p) { std::cout << p.first << std::endl; };
那么你可以在方向上分支:
if(forward)
std::for_each(std::begin(m), std::end(m), f);
else
std::for_each(std::rbegin(m), std::rend(m), f);