在c++中编写for/else的简明方法
Concise way to write a for/else in C++?
在我编写的一些代码中,我有一个for循环遍历map:
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
的启发,我尝试了这个结构,将else部分放在正确的位置[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++中没有简洁的空的反义词;-)
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 多个 if-else 测试的更简单方法
- 有没有简单的方法可以在 if-else 链的末尾做与 else 相反的事情
- 具有"else if"方法问题 C++ 的基本计算器
- 编写 if then else 类型语句的简洁方法
- 用c++编写if-then-else语句的更有效方法
- typedef的替代品或将typedef与if-else一起使用的正确方法
- 在c++中编写for/else的简明方法