Sorting Object Pointers in C++

Today I was working on my computer animation project using C++, Boost, STL, and OpenGL. I ran into a few hitches related to pointers and the STL (Standard Template Library) and I decided to blog about it. Problem: You can't override the default operator<  for the pointer type, so you have to make a class/structure that defines an operator() function, which is the function pointer. Any attempt to create a operator< (const Frame *lhs, const Frame *rhs) will be ignored. You might find yourself wondering why objects are being sorted by memory address (pointer address), rather than your defined method. Here's an excerpt from my code. (Thanks to CopySourceAsHTML)

// Frame.h

/** A compare class used for Frame pointers.*/

class FrameComparer {

public:

bool operator() ( const Frame *lhs, const Frame *rhs) {

return (*lhs).getTime() < (*rhs).getTime();

}

};

...

//FrameViewer.cpp

/** Adds frames to be viewed at a later time */

void FrameViewer::addFrames(std::vector<Frame *> frames) {

// Append the new frames to current frames

_frames.insert(_frames.end(), frames.begin(), frames.end());

// Sort

std::sort(_frames.begin(), _frames.end(), FrameComparer());

}

Summary:

I had a STL vector full of pointer objects, but the only way I was comparing was by pointer address until I created the FrameComparer class. With the class and an compare object defined I'm able to override the sort methods comparison behavior. This way will correctly sort the Frame objects by time value, rather than pointer address.

References:

Function pointers

[ad#Large Box]