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:
3 Responses to Sorting Object Pointers in C++
Leave a Reply Cancel reply
Artwork Evolution
Facebook
@PaulSolt
- RT @flexibits: Happy 1st Birthday, Fantastical! http://t.co/bIcVDgbZ 2012/05/18
- @IAmReynolds thanks, I think it's the color choice that made it look good. Gradient colors similar to the line color. 2012/05/17
- @rwenderlich I'm interested if this is still an option. I did a text-based risk game back in high school. It could work for an iPad app. 2012/05/16
Github
Tags
animation App Store Artwork Evolution Boost Boot Camp C++ cross platform development Dual Monitors function pointers Gears of War 2 gestures git GLUT inheritance iOS iPad iPhone Macbook Pro Mac OS X MacPorts member functions Objective-C OCUnit OpenGL player/stage polymorphism presentation programming remote control RIT SCM slides static methods STL svn 1.6 tdd testable code testing unit testing version control Windows XP Xbox 360 Xcode xcode 3.1.2







Your example is great and helped me a lot – thanks!
You’re welcome!
I wasn’t able to sort the class objects in the vector, your example helped me to sort that..
Thanks a lott…