Moaz ELdeen
Moaz ELdeen

Reputation: 249

Distance between two std::List

I have two std::list, which each one has a positional vector m_Pos. I'm newbie to std::list, and I would to calculate the distance between each index in those two lists and store them in an array. This is what I have done, I dont know if it is the correct way or not

The problem is the dir vector which has the distances are not in ordered manner, I want for example to store the distane between positions Acurrent and Aprev, Bcurrent, Bprev, to be stored in order in the dir vector so that I can correlate later between them, so that I say dir[0] is the distance between Acurr, Aprev..etc

if(objs.size() == m_prev_objs.size())
{
    std::vector<Vec2f> dir;
    std::list< Obj >::iterator prevIter = m_prev_objs.begin();
    std::list< Obj >::iterator currIter = objs.begin();

    //  Vec2f dis = currIter->m_Pos - prevIter->m_Pos;  
    for (std::list< Obj >::iterator currIter = objs.begin(); currIter != objs.end(); ++currIter ) 
    {

        dir.push_back(currIter->m_Pos - prevIter->m_Pos);

    }

           prevIter++;

}

Upvotes: 1

Views: 565

Answers (1)

111111
111111

Reputation: 16148

Consider using standard algorithms, note the action can be lambda if you have access to C++11

 inline Vec2f action(const Objs& o1, const Objs& o2) {
       return o1->m_Pos
            - o2->m_Pos;
 }


 //elsewhere
 std::vector<Vec2f> dir;
 dir.reserve(objs.size());

 std::transform(
      objs.begin(),        
      objs.end(), 
      m_prev_objs.begin(), 
      std::back_inserter(dir),
      action
 );

http://en.cppreference.com/w/cpp/algorithm/transform

http://en.cppreference.com/w/cpp/iterator/back_inserter

Upvotes: 5

Related Questions