【问题标题】:C++98 Valid use of "for_each" in the codeC++98 代码中“for_each”的有效使用
【发布时间】:2014-11-13 14:06:43
【问题描述】:

我想直接进入代码;这是我的结构:

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

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

这是我的功能:

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

这是我在字段类成员函数中的 for 循环。

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

当我的向量成员只是应用函数的参数之一时,是否可以在这里使用 for_each?

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

【问题讨论】:

  • 什么?你想使用什么 for_each? c++11基于范围的for循环?
  • 编辑:我只能使用 C++98

标签: c++ foreach


【解决方案1】:

你可以,虽然我想说这不会让它变得更好,因为你需要为typeDetection定义一个函子,然后将它传递给for_each(不要忘记传递thisNNSearch 在创建仿函数时将其值传递给函数,以便在需要时将它们传递给 typeDetection

在这种情况下,我会考虑保持 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 衬垫循环。

【讨论】:

  • 是的,我有几个向量需要应用这个函数。
  • @H'H 然后for_each 可以在这里应用,如果您认为必须定义和创建仿函数并不会太麻烦以节省 4 衬套循环。
【解决方案2】:

是的,这应该可行(尽管我无法测试它,因为这里没有真正定义任何内容)。而不是这部分代码,

   vector< pnt > oldpnTs;

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

你可以试试这个(在 C++14 中):

   vector< pnt > oldpnTs;
   NNSerach all = ALL;
   // ...
   std::for_each(oldpnTs.begin(), oldpnTs.end()
               , [this, all](auto& x) {this->typeDetection(x, all, *this);});



编辑: 在 C++98 中,您当然可以使用仿函数来修复 pnt&amp; 旁边的其他变量,而不是 lambda。或者您可以使用boost::lambdaboost::bind

【讨论】:

  • 您的编辑是在我尝试之后出现的。如果你没问题,我会让它保持不变。
  • 虽然我不能使用 C++14,但很高兴看到它在新的 C++ 标准下是如何工作的。
【解决方案3】:

当你使用 C++98 时,你应该使用仿函数自己实现 lambda 函数:

#include <vector>
#include <algorithm>

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

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

class fieldclass;

class TypeDetection
{
public:
    TypeDetection(const NNSerach NNType, const fieldclass& field) : _NNType(NNType), _field(field){}
    void operator() (pnt& PNT)
    {
        typeDetection(PNT, _NNType, _field);
    }
private:
    void typeDetection( pnt& PNT, const NNSerach NNType, const fieldclass& field ){}

    const fieldclass& _field;
    const NNSerach _NNType;
};

class fieldclass
{
public:
    void Do()
    {
        std::vector<pnt> oldpnTs;
        std::for_each(oldpnTs.begin(), oldpnTs.end(), TypeDetection(ALL, *this));
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-27
    • 2023-02-03
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 2014-12-17
    相关资源
    最近更新 更多