Breaking in std::for_each loop

前端 未结 7 1433
南方客
南方客 2021-01-01 10:37

While using std::for_each algorithm how do I break when a certain condition is satisfied?

7条回答
  •  南方客
    南方客 (楼主)
    2021-01-01 11:16

    You can use std::any_of (or std::all_of or std::none_of) e.g. like this:

    std::vector a;
    // ...     
    std::all_of(a.begin(), a.end(), [&](int val) { 
      // return false if you want to break, true otherwise
      });
    

    However, this is a wasteful solution (return values are not really used for anything), and you're better off writing you own loop.

提交回复
热议问题