Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 788
m33p Avatar asked Aug 08 '14 16:08

m33p


People also ask

Is there a FOR else in C?

C has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

Can we use else with for loop in C?

In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops.

What is else loop?

Python - else in LoopThe statements in the else block will be executed after all iterations are completed. The program exits the loop only after the else block is executed. The output of the above code confirms that the else block in the for loop will be executed while the number is in the range.

What is for else and while else?

What is For Else and While Else in Python? For-else and while-else are useful features provided by Python. In simple words, you can use the else block just after the for and while loop. Else block will be executed only if the loop isn't terminated by a break statement.


1 Answers

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
}
like image 94
Havenard Avatar answered Oct 27 '22 06:10

Havenard