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?
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.
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.
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 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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With