我有一张地图,里面有一些条目。我想基于某些条件使用相同的for循环以升序或降序迭代映射。我该怎么办?
示例:
if(x)
{
// Traverse in reverse order
// If i declare rbegin and rend iterator here
}
else
{
// Traverse in ascending order
// If i declare begin and end iterator here
}
// Now using same for loop how can i achieve this? Below for loop should use either rbegin or begin based on above condition. Is it possible?
for(;;;)
{
}
更详细的例子:
if(getSort() == DESCENDING) {
std::map<int,int>::reverse_iterator aItrBegin = map.rbegin();
std::map<int,int>::reverse_iterator aItrEnd = map.rend();
}
else {
std::map<int,int>::iterator aItrBegin = map.begin();
std::map<int,int>::iterator aItrEnd = map.end();
}
for(; aItrBegin!=aItrEnd; ++aItrBegin) // Here aItrBegin and aItrEnd are not accessible
cout << "Inside output \n";
}
答案 0 :(得分:5)
将循环逻辑移到lambda中:
def some_view(requests):
...
tag = request.GET.get("tag", 0)
或者如果您经常需要它,可以使用参数来实现您自己的 auto logic = []( const auto &p ) {
// loop logic
};
if( x ) std::for_each( map.rbegin(), map.rend(), logic );
else std::for_each( map.begin(), map.end(), logic );
模板函数,该参数定义了方向。