繁体   English   中英

在C ++中编写for / else的简明方法?

[英]Concise way to write a for/else in C++?

在我正在处理的一些代码中,我有一个迭代遍历地图的for循环:

for (auto it = map.begin(); it != map.end(); ++it) {

    //do stuff here
}

我想知道是否有某种方法可以简明扼要地写出以下内容:

for (auto it = map.begin(); it != map.end(); ++it) {
    //do stuff here
} else {
    //Do something here since it was already equal to map.end()
}

我知道我可以改写为:

auto it = map.begin();
if (it != map.end(){

    while ( it != map.end() ){
        //do stuff here
        ++it;
    }

} else {
    //stuff
}

但有没有更好的方法不涉及包装if语句?

明显...

if (map.empty())
{
    // do stuff if map is empty
}
else for (auto it = map.begin(); it != map.end(); ++it)
{
    // do iteration on stuff if it is not
}

顺便说一下,既然我们在这里谈论C ++ 11,你可以使用这个语法:

if (map.empty())
{
    // do stuff if map is empty
}
else for (auto it : map)
{
    // do iteration on stuff if it is not
}

如果你想在C ++中有更多疯狂的控制流,你可以用C ++ 11编写它:

template<class R>bool empty(R const& r)
{
  using std::begin; using std::end;
  return begin(r)==end(r);
}
template<class Container, class Body, class Else>
void for_else( Container&& c, Body&& b, Else&& e ) {
  if (empty(c)) std::forward<Else>(e)();
  else for ( auto&& i : std::forward<Container>(c) )
    b(std::forward<decltype(i)>(i));
}

for_else( map, [&](auto&& i) {
  // loop body
}, [&]{
  // else body
});

但我建议不要这样做。

受到Havenard的else for启发,我尝试了这个结构,其他部分坐在正确的位置[1]

if (!items.empty()) for (auto i: items) {
    cout << i << endl;
} else {
    cout << "else" << endl;
}

完整演示

我不确定我是否会在实际代码中使用它,也因为我不记得我错过了for循环的else子句的单个案例,但我承认只有今天我才知道python有它。 我从你的评论中读到了

//Do something here since it was already equal to map.end()

...你可能没有提到python的for-else ,但也许你也这么做了 - python程序员似乎也对这个功能有疑问


[1]不幸的是,在C ++中没有简洁的反面是空的 ;-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM