A short way to write for / else in C ++?

In some code that 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 any way to write something briefly into action:

 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 that I can rewrite it 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 isn't related to wrapping into an if statement?

+6
source share
3 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 here with C ++ 11, 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 } 
+20
source

If you need a more crazy control flow in C ++, you can write it in C ++ 11:

 template<class R>bool empty(R const& r) { using std::begin; using std::end; return begin(r)==end(r); } template<class Container, class Body, class Else> void for_else( Container&& c, Body&& b, Else&& e ) { if (empty(c)) std::forward<Else>(e)(); else for ( auto&& i : std::forward<Container>(c) ) b(std::forward<decltype(i)>(i)); } for_else( map, [&](auto&& i) { // loop body }, [&]{ // else body }); 

but I would advise doing it.

+3
source

Inspired by Havenard else for , I tried this structure with the else part sitting in the right place [1] .

 if (!items.empty()) for (auto i: items) { cout << i << endl; } else { cout << "else" << endl; } 

( full demo )

I am not sure if I will use it in real code, also because I do not remember a single case where I did not have the else clause for the for loop, but I have to admit that only today I found out that python has this . I read from your comment

 //Do something here since it was already equal to map.end() 

... that you probably do not mean python for-else , but perhaps you did - also python programmers have their own problems with this function .


[1] Unfortunately, in C ++ there is no brief opposite is empty -

0
source

Source: https://habr.com/ru/post/973553/


All Articles