c++c++11for-loopfor-else

Concise way to write a for/else in C++?


In some code I was working on, I have a for loop that iterates through a map:

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

    //do stuff here
}

And I wondered if there was some way to concisely write something to the effect of:

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

I know I could rewrite as:

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

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

} else {
    //stuff
}

But is there a better way that doesn't involve wrapping in an if statement?


Solution

  • Obviously...

    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
    }
    

    By the way, since we are talking C++11 here, you can use this syntax:

    if (map.empty())
    {
        // do stuff if map is empty
    }
    else for (auto it : map)
    {
        // do iteration on stuff if it is not
    }