簡體   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