David1909
July 18th, 2002, 02:20 PM
I have vector <Class> array, which contain a sequence of class instances, now could I sort the array accoding to the member value of class?
Thanks
Thanks
|
Click to See Complete Forum and Search --> : Stl sorting question.... David1909 July 18th, 2002, 02:20 PM I have vector <Class> array, which contain a sequence of class instances, now could I sort the array accoding to the member value of class? Thanks jfaust July 18th, 2002, 02:27 PM You need to define your own predicate. Check out this thread. edited: fixed link http://www.codeguru.com/forum/showthread.php?s=&threadid=199819 Jeff David1909 July 18th, 2002, 02:44 PM But, how to define my own predicate, could you give a example for following code? thanks: class Me { int m_x; public: int GetX() { return m_x; } void SetX(int x) { m_x=x; } }; void main() { vector<Me> ArrayMe; for(int i=0; i<10; i++) { int x=rand()%10; Me me; me.setx(x); Array.push_back(); } //here I want ro sort ArrayMe according to m_x value // how do I do? } thanks jfaust July 18th, 2002, 03:00 PM First of all, my link was bad. I fixed it. Second, a better and easier would be to define operator<. Try this: #include <vector> #include <algorithm> using namespace std; class Me { int m_x; public: int GetX() const { return m_x; } void SetX(int x) { m_x=x; } bool operator<(const Me& rhs) const { return GetX() < rhs.GetX(); } }; void main() { vector<Me> ArrayMe; for(int i=0; i<10; i++) { int x=rand()%10; Me me; me.SetX(x); ArrayMe.push_back(me); } std::sort(ArrayMe.begin(), ArrayMe.end()); } David1909 July 18th, 2002, 03:09 PM Thanks it is works! codeguru.com
Copyright Internet.com Inc., All Rights Reserved. |