7

在我正在处理的一些代码中,我有一个遍历地图的 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 语句中?

4

3 回答 3

22

明显地...

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
}
于 2014-08-08T16:56:27.337 回答
5

如果你想在 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
});

但我建议不要这样做。

于 2014-08-08T18:14:57.540 回答
0

Havenard 的else for启发,我尝试了这种结构,其中 else 部分位于正确的位置[1]

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

完整演示

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

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

...您可能不是指python 的for-else,但也许您确实提到了 - python 程序员似乎也对这个功能有问题


[1]不幸的是,在 C++中没有简洁的对立面 is empty ;-)

于 2014-11-28T11:45:30.610 回答