With almost all code I write, I am often dealing with set reduction problems on collections that ultimately end up with naive "if" conditions inside of them. Here's a simple example:
for(int i=0; i<myCollection.size(); i++) { if (myCollection[i] == SOMETHING) { DoStuff(); } }
With functional languages, I can solve the problem by reducing the collection to another collection (easily) and then perform all operations on my reduced set. In pseudocode:
newCollection <- myCollection where <x=true map DoStuff newCollection
And in other C variants, like C#, I could reduce with a where clause like
foreach (var x in myCollection.Where(c=> c == SOMETHING)) { DoStuff(); }
Or better (at least to my eyes)
myCollection.Where(c=>c == Something).ToList().ForEach(d=> DoStuff(d));
Admittedly, I am doing a lot of paradigm mixing and subjective/opinion based style, but I can't help but feel that I am missing something really fundamental that could allow me to use this preferred technique with C++. Could someone enlighten me?
You can't break out of if statement until the if is inside a loop. The behaviour of the break statement is well specified and, generally, well understood.
Yes it is perfectly correct to do so.
The break is a jump statement that can break out of a loop if a specific condition is satisfied. We can use the break statement inside an if statement in a loop. The main purpose of the break statement is to move the control flow of our program outside the current loop.
2 Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant. Since there's no such requirement for while loop (if the condition is omitted), I believe, it's left to the implementation of compiler.
IMHO it's more straight forward and more readable to use a for loop with an if inside it. However, if this is annoying for you, you could use a for_each_if
like the one below:
template<typename Iter, typename Pred, typename Op> void for_each_if(Iter first, Iter last, Pred p, Op op) { while(first != last) { if (p(*first)) op(*first); ++first; } }
Usecase:
std::vector<int> v {10, 2, 10, 3}; for_each_if(v.begin(), v.end(), [](int i){ return i > 5; }, [](int &i){ ++i; });
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With