【发布时间】:2023-03-29 17:06:01
【问题描述】:
我有一个方法应该根据条件向前或向后迭代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>?
【问题讨论】:
-
在
<algorithm>中,您有模板。 -
@LogicStuff 我知道这一点,但我不必编写它们 - 只是一个 lambda,在这种情况下我会认为它更清晰(可读性)
-
你可以看到this并阅读示例,他们使用迭代器。
-
@AlejandroCortes ??
标签: c++ iterator reverse-iterator