在我正在处理的一些代码中,我有一个迭代遍历地图的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 }