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

时间:2014-08-08 16:52:44

标签: c++ c++11 for-loop for-else

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

3 个答案:

答案 0 :(得分:20)

...显然

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
}

答案 1 :(得分:3)

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

但我建议反对。

答案 2 :(得分:0)

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

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

full demo

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

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

......你可能不是指python's for-else,但也许你指的是 - python programmers seem to have their problems with this feature


不幸的是,

[1] 在C ++中没有concise opposite of is empty; - )