I am using the STL container vector that helds pointers of my defined class.
My question now:
How can I define a "sort predicate" for the STL algorithm sort in the case that my vector helds pointers of my class instances and not the instances itself?
Here are pieces of my code:
The class "Track" has a vector of the TrackPoint pointers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class TrackPoint
{
public:
TrackPoint();
virtual ~TrackPoint();
int SetVelocity(double velocity);
double GetVelocity();
private:
double m_v; // [m/s]
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class Track
{
public:
Track();
virtual ~Track();
int CalculateVelocityLimit();
private:
void Reset();
typedef std::vector<TrackPoint*> PointVector;
PointVector m_track_list;
};
class TrackPoint
{
public:
TrackPoint();
virtual ~TrackPoint();
int InitTrackPoint(int index, double v);
int SetVelocity(double velocity);
int GetIndex();
double GetVelocity();
staticbool ComparePredicateVelocity(TrackPoint* point1, TrackPoint* point2)
{
return (point1->GetVelocity() < point2->GetVelocity());
}
private:
int m_index; // [-]
double m_v; // [m/s]
};
After the sort of the vector<TrackPoint*> with the predicate "m_v" if would like to find the element in the vector with the previous index regarding the first element after sorting it.
std::sort(track_todo.begin(), track_todo.end(), TrackPoint::ComparePredicateVelocity);
while(track_todo.size() > 0)
{
TrackPoint *p_current_trackpoint = new TrackPoint();
p_current_trackpoint->InitTrackPoint(track_todo[0]->GetIndex(),
track_todo[0]->GetDistance(),
track_todo[0]->GetCurvature(),
track_todo[0]->GetVelocityDmd(),
track_todo[0]->GetVelocity());
track_todo.erase(track_todo.begin());
// *** Deceleration ***
// check if current point is not the first point
if (p_current_trackpoint->GetIndex() > 0)
{
TrackPoint *p_previous_trackpoint = new TrackPoint();
p_previous_trackpoint = std::binary_search(m_track_list.begin(), m_track_list.end(), p_current_trackpoint->GetIndex() - 1);
}
}
I am not sure how to use the binary_search algorithm in the case it doesn't search directly for a vaue in the vector but for a member of one element.
In fact I would like to get back the Trackoint* of this element...