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
- I just unlocked the "Super Swarm Sunday" badge on @foursquare! Go team! http://t.co/jg1u7Blz 5 hours ago
- I'm at Super Swarm Sunday w/ @michaelmurphy @aaronfeng @benatnewdigs @unystartups @amblatx1 @skeeterharris @ianmikutel http://t.co/pPsid8Aj 5 hours ago
- RT @mattgemmell: CGPathCreateCopyByStrokingPath() (new in iOS 5 / Lion). I've wanted this function for as long as I've written UI code. ... 2012/02/04
Github
Tags
animation App Store Artwork Evolution Boost Boot Camp C++ cross platform default values development Dual Monitors function pointers Gears of War 2 git GLUT graphics ImagineRIT Impulse inheritance iOS iPad iPhone Macbook Pro Mac OS X MacPorts member functions Objective-C OpenGL PAX 10 player/stage polymorphism programming remote control RIT Robot robotics SCM static methods STL svn 1.6 version control Windows XP Xbox 360 Xcode xcode 3.1.2 XNA







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…