Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert for loop to STL for_each statement

I would like to convert my for loop to STL std::for_each loop.

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

Actually I was planning to use parallel STL from g++4.4

 g++ -D_GLIBCXX_PARALLEL -fopenmp

which is allow to run code in parallel without changes if the code is written in standard STL library.

like image 732
Arman Avatar asked Mar 09 '10 18:03

Arman


2 Answers

You need to seperate out the loop body into a seperate function or functor; I've assumed all the undeclared variables are member variables.

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));
}
like image 64
JoeG Avatar answered Oct 03 '22 20:10

JoeG


class F {
   public:
   void operator()(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);
   } 
   F(int[] r): //and other parameters should also be passed into the constructor
      r_(r) {}
   void:
   int[] r_; // refers to R[ii] array
   // and other parameters should also be stored
};

F f(R); // pass other parameters too  
for_each(&indexR[0], &indexR[iR20], f);

However it might not be a good idea to use this "automatic parallelization" since you need to keep in mind the grainsize of each parallel computation -- I am not sure how well the compiler takes the grain size into account.

like image 22
amit kumar Avatar answered Oct 03 '22 20:10

amit kumar