Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid "for" loops with an "if" condition inside them with C++?

Tags:

c++

c++11

c++14

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?

like image 671
Darkenor Avatar asked Jul 15 '16 14:07

Darkenor


People also ask

Can you break out of an if statement in C?

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.

Can we write for loop without condition in C?

Yes it is perfectly correct to do so.

How do you get out of a if loop?

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.

What happens if condition not given in for 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.


1 Answers

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

like image 82
101010 Avatar answered Oct 07 '22 13:10

101010