C ++ 98有效使用“for_each”在代码中 [英] C++98 Valid use of "for_each" in the code

查看:126
本文介绍了C ++ 98有效使用“for_each”在代码中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想直接在代码中;这是我的结构:

  struct pnt {
mesh :: Point _point;
pnt_type _type;
bool _aux;
};

枚举NNSerach {A_NN = 0,B_NN,C_NN,ALL};

这里是我的功能:

  void typeDetection(pnt& PNT,const NNSerach NNType,const fieldclass& field)


$ b b

这里是我的for循环里面的fieldclass的成员函数。

  pnt> oldpnTs; 
...
for(size_t iter = 0; iter< oldpnTs.size(); iter ++)
{
typeDetection(oldpnTs [iter],ALL,* this) ;
}

这里可以使用for_each,当我的向量成员只有一个应用函数的参数?



EDIT :我只能使用 C ++ 98
我想为oldpnTs向量的每个成员应用typeDetection函数。

解决方案

你可以,更好的我会说,因为你需要定义一个函数 typeDetection ,然后将它传递给 for_each (不要忘记在创建它时将 NNSearch 值传递给函子,



在这种情况下,我会考虑保持for循环,由于代码以其当前形式可读,(除非)必须对具有可能不同大小的多个此类向量执行此操作,因此会产生以下结果:

  std :: for_each(std :: begin(oldpnTs),std :: end(oldpnTs),typeDetectionFunctor); 
std :: for_each(std :: begin(oldpnTs),std :: end(oldpnTs2),typeDetectionFunctor);
std :: for_each(std :: begin(oldpnTs),std :: end(oldpnTs3),typeDetectionFunctor);
std :: for_each(std :: begin(oldpnTs),std :: end(oldpnTs4),typeDetectionFunctor);
// ...

而不是像你目前的多个4衬垫循环。 / p>

I want to go directly in the code; Here is my struct:

struct pnt {
  mesh::Point _point;
  pnt_type _type;
  bool _aux;
  };

enum NNSerach {A_NN = 0, B_NN, C_NN, ALL}; 

and here is my function:

void typeDetection( pnt& PNT, const NNSerach NNType, const fieldclass& field )

Here is my for loop inside a member function of the fieldclass.

vector< pnt > oldpnTs;
...
  for(size_t iter = 0; iter < oldpnTs.size(); iter++ )
  {
    typeDetection(oldpnTs[iter], ALL, *this);
  }

Is it possible to use for_each here, when my vector member is only one of the arguments of the applied function?

EDIT: I can only use C++98 I want to apply typeDetection function for each member of the oldpnTs vector.

解决方案

You could, though that wouldn't make it that much better I'd say, as you'd need to define a functor for typeDetection, and then pass it to for_each (don't forget to pass this and the NNSearch value to the functor when you create it so you can pass them to typeDetection when needed).

In this case I'd consider keeping the for loop as it is, as the code is readable in its current form, unless you have to perform this operation on multiple such vectors with potentially different sizes, resulting in the following:

std::for_each(std::begin(oldpnTs), std::end(oldpnTs), typeDetectionFunctor);
std::for_each(std::begin(oldpnTs), std::end(oldpnTs2), typeDetectionFunctor);
std::for_each(std::begin(oldpnTs), std::end(oldpnTs3), typeDetectionFunctor);
std::for_each(std::begin(oldpnTs), std::end(oldpnTs4), typeDetectionFunctor);
//...

instead of multiple 4 liners loop like you currently have.

这篇关于C ++ 98有效使用“for_each”在代码中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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