小编m33*_*33p的帖子

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

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

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

    //do stuff here
}
Run Code Online (Sandbox Code Playgroud)

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

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

我知道我可以改写为:

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

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

} else {
    //stuff
}
Run Code Online (Sandbox Code Playgroud)

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

c++ for-loop c++11 for-else

6
推荐指数
2
解决办法
2576
查看次数

标签 统计

c++ ×1

c++11 ×1

for-else ×1

for-loop ×1