m33*_*33p 6 c++ for-loop c++11 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语句?
Hav*_*ard 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
}
Run Code Online (Sandbox Code Playgroud)
顺便说一下,既然我们在这里谈论C++ 11,你可以使用这个语法:
if (map.empty())
{
// do stuff if map is empty
}
else for (auto it : map)
{
// do iteration on stuff if it is not
}
Run Code Online (Sandbox Code Playgroud)
如果你想要更疯狂的 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
});
Run Code Online (Sandbox Code Playgroud)
但我建议不要这样做。