在C中写一个forelse的简洁方法?

在C中写一个forelse的简洁方法?,第1张

概述在我正在处理的一些代码中,我有一个迭代遍历地图的for循环: for (auto it = map.begin(); it != map.end(); ++it) { //do stuff here} 我想知道是否有某种方法可以简明扼要地写出以下内容: for (auto it = map.begin(); it != map.end(); ++it) { //do stuff 在我正在处理的一些代码中,我有一个迭代遍历地图的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中写一个for/else的简洁方法?全部内容,希望文章能够帮你解决在C中写一个for/else的简洁方法?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1238286.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存