Original Post
Hi, I am using C++ and Direct3d9. I have a list of RECTS,eg list lstRectList; I want to sort either ascending or descending by a value, eg sort by RECT.left So how would I do it?
struct MyCompare{ bool operator() (const RECT& a, const RECT& b) {return a.left < b.left;}}std::sort(lstRectList.begin(),lstRectList.end(),MyCompare);#include <iostream>#include <list>#include <algorithm>bool myPred(int i1, int i2){ return (i1 < i2);}int main(){ std::list<int> myInt; myInt.push_back(1); myInt.push_back(2); myInt.push_back(0); std::copy(myInt.begin(), myInt.end(), std::ostream_iterator<int>(std::cout, " ")); myInt.sort(myPred); std::copy(myInt.begin(), myInt.end(), std::ostream_iterator<int>(std::cout, " ")); std::cin.get(); return 0;}bool MyListSorter( RECT & a, RECT & b ){ return a.left < b.left;} ... lstRectList myList; myList.sort( MyListSorter ); ... or class MyListSorter{public: bool operator()( RECT & a, RECT & b ) { return a.left < b.left; }}; ... lstRectList myList; myList.sort( MyListSorter() ); ...
struct MyRECT{ int m_nWidth; int m_nHeight; int m_nArea;};list <MyRECT*> m_lstRECTS;//list::sortm_lstRECTS.sort( SortList() );//sortlist function to use with list::sortbool SortList(MyRECT *a,MyRECT *b){ return a->m_nArea < b->m_nArea;}Quote:std::vector is *far* slower for insertion, except for at the end. It's better for some things (random access, O(1) lookup), but worse for others. I wouldn't say that vector is "usually better" by any means.
Original post by ace_lovegrove
vector is usually better.
Quote:
just literally copy/past EvilSteve's response and fillout the comparitor differently if you want.
Quote:
I tried using the below method, but I can't figure it out:
Quote:D'oh, you're right. I didn't know that...
Original post by Anonymous Poster Quote:
Original post by Evil Steve
EDIT: Or you could make your own RECT structure, and add an operatorstd::sort(lstRectList.begin(),lstRectList.end());
std::sort does NOT work on std::list::iterator's because they're not random access.
This topic has been locked by a moderator. New replies are not allowed.
With your permission, GameDev.net uses analytics cookies to understand how people use the platform. You can accept analytics or continue with necessary cookies only. Learn more