简体   繁体   中英

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?

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 want 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'd advise against it.

Inspired by Havenard's 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'm not sure if I would use it in real code, also because I do not remember a single case that I was missing an else clause for the for loop, but I've to admit that only today I learned that python has it. I read from your comment

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

...that you are probably not referring to python's for-else , but maybe you did - also python programmers seem to have their problems with this feature .


[1] unfortunately, there is no concise opposite of is empty in C++ ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM