Breaking in std::for_each loop

前端 未结 7 1455
南方客
南方客 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:14

    You throw an exception. Whether or not it's a good idea is sort of a style question, pace @Dan, but may be more of an issue with your design. for_each is intended for a sort of functional-programming style, which implicitly assumes that your function can be applied uniformly across the set. So, if you do need to break, that could be consiered an unusual condition, and therefore worthy of an exception.

    The other solution, and a more "functional" solution, is to write your function so that if it shouldn't have an effect on some applications, then write it to have no effect. So, for example, if you had a summing function, have it add 0 in the cases you would have "broken" from.

提交回复
热议问题