如何将for循环转换为STL for_each语句

Arm*_*man 5 c++ parallel-processing stl

我想将我的for循环转换为STL std :: for_each循环.

 bool CMyclass::SomeMember()
 {
    int ii;
        for(int i=0;i<iR20;i++)
            {
              ii=indexR[i];
              ishell=static_cast<int>(R[ii]/xStep);
              theta=atan2(data->pPOS[ii*3+1], data->pPOS[ii*3]);
              al2[ishell] += massp*cos(fm*theta);
            }
 }
Run Code Online (Sandbox Code Playgroud)

实际上我打算从g ++ 4.4中使用并行STL

 g++ -D_GLIBCXX_PARALLEL -fopenmp
Run Code Online (Sandbox Code Playgroud)

如果代码是在标准STL库中编写的,则允许并行运行代码而不进行更改.

Joe*_*oeG 5

你需要将循环体分离成一个单独的函数或函子; 我假设所有未声明的变量都是成员变量.

void CMyclass::LoopFunc(int ii)  {
    ishell=static_cast<int>(R[ii]/xStep);
    theta=atan2(data->pPOS[ii*3+1],
    data->pPOS[ii*3]);
    al2[ishell] += massp*cos(fm*theta);
}

bool CMyclass::SomeMember()  { 
    std::for_each(&indexR[0],&indexR[iR20],std::tr1::bind(&CMyclass::LoopFunc,std::tr1::ref(*this));
}
Run Code Online (Sandbox Code Playgroud)