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

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

本文关键字:else 方法 for c++      更新时间:2023-10-16

在我编写的一些代码中,我有一个for循环遍历map:

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的启发,我尝试了这个结构,将else部分放在正确的位置[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++中没有简洁的空的反义词;-)