-3

Consider a case of a for inside an other for

int f( ... )
{
  for (int i = start_a; i < end_a; i++)
  {
    for (int j = start_b; j < end_b; j++)
    {
      // make some computation
      if( i_must_exit == true)
      {
        // exit from all for
      }
    }
  }

  // I want arrive here
}

We want to break from both for loops. This isn't easy in C++03 without factoring out the inner function, throwing an exception, etc. I was wondering if C++11 introduced a mechanism by which to do this.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
Gian Lorenzo Meocci
  • 1,136
  • 2
  • 14
  • 23

3 Answers3

11

I think the best solution is to use iterators and algorithms, like std::find_if.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
3

I think that the best solution is using a lambda ... something like this:

int f()
{
  [&]{
    for (int i = start; i < end; i++)
    {
      for (int j = start_; j < end_; j++)
      {
        // make some computation
        if( i_must_exit == true)
        {
          // exit from all for
          return;
        }
      }
    }
  }(); // execute this code now!

  // continue with computation
}
Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
Gian Lorenzo Meocci
  • 1,136
  • 2
  • 14
  • 23
  • 1
    Note that this isn't so much using a lambda as almost refactoring the loop into its own function. Give it a good, explicit name as to what it does and you've got yourself some nice separation of concerns. That the refactored code appears in a lambda instead of a bona-fide C++ function a purely syntactic difference. (You might also want to avoid default captures here.) – Luc Danton Apr 26 '13 at 23:04
  • 1
    @LucDanton I'd drop the `auto L =` and the `()` and leave the default capture. Then the lambda becomes a control structure that allows you to break out via `return` from anywhere in the inner scope. Actually as written it didn't compile (void lambda cannot have its return value stored), so I made my changes and it now compiles. – Yakk - Adam Nevraumont Apr 27 '13 at 03:31
0
int f( ... )
{
  bool b = false;

  for (int i = start_a; i < end_a; i++)
  {
    for (int j = start_b; j < end_b; j++)
    {
      // make some computation
      if( i_must_exit == true)
      {
         b = true;
         break;
      }
    }
    if (b)
        break;
  }

  // I want arrive here
}
Andrew Tomazos
  • 66,139
  • 40
  • 186
  • 319