我如何避免“for”循环具有“if”条件里面用C ++? [英] How can I avoid "for" loops with an "if" condition inside them with C++?

查看:119
本文介绍了我如何避免“for”循环具有“if”条件里面用C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几乎所有的代码我写,我经常处理集合减少集合问题,最终结果是天真的if条件里面。这里有一个简单的例子:

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

在其他C类型中,像C#,我可以使用

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));

诚然,我做了很多范式混合和主观/意见的风格, t帮助,但觉得我缺少一些真正根本的东西,可以允许我使用这个首选的技术与C ++。

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?

推荐答案

IMHO更直接,更容易阅读,使用一个for循环与一个if里面。但是,如果这很烦人,你可以使用 for_each_if ,如下所示:

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;
  }
}

使用程序:

std::vector<int> v {10, 2, 10, 3};
for_each_if(v.begin(), v.end(), [](int i){ return i > 5; }, [](int &i){ ++i; });

在线演示

这篇关于我如何避免“for”循环具有“if”条件里面用C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆