446,159 Members | 938 Online
Need help? Post your question and get tips & solutions from a community of 446,159 IT Pros & Developers. It's quick & easy.

# Sorting by class value

 P: n/a Suppose I have: #include using std::vector; class C { public: int a,b; }; int main() { vector vecC; //Populate vecC how do i now sort according to a or b?? do I pass in a function pointer to sort(.....)?? } Regards Mike Jul 22 '05 #1
4 Replies

 P: n/a "Michael" writes: [snip] how do i now sort according to a or b?? do I pass in a function pointer to sort(.....)?? You may use either a pointer to a function or a functor: #include #include using std::vector; using std::sort; class C { public: int a,b; }; bool comp(C const& lhs, C const& rhs){return lhs.a < rhs.a;} struct compare { bool operator()(C const& lhs, C const& rhs){return lhs.a < rhs.a;} }; int main() { vector vecC; //Use pointer to function. sort(vecC.begin(),vecC.end(),comp); //Use functor. sort(vecC.begin(),vecC.end(),compare()); } Jul 22 '05 #2

 P: n/a Michael wrote: Suppose I have: #include using std::vector; class C { public: int a,b; }; int main() { vector vecC; //Populate vecC how do i now sort according to a or b?? do I pass in a function pointer to sort(.....)?? } Regards Mike Create an ordering functor: class a_less_b { public: bool operator() (const C& c1, const C& c2) {return c1.a < c2.b;} }; Use the function when sorting the vector: std::sort(vecC.begin(), vecC.end(), a_less_b()); -- Thomas Matthews C++ newsgroup welcome message: http://www.slack.net/~shiva/welcome.txt C++ Faq: http://www.parashift.com/c++-faq-lite C Faq: http://www.eskimo.com/~scs/c-faq/top.html alt.comp.lang.learn.c-c++ faq: http://www.raos.demon.uk/acllc-c++/faq.html Other sites: http://www.josuttis.com -- C++ STL Library book Jul 22 '05 #3

 P: n/a Michael wrote: Suppose I have: #include using std::vector; class C { public: int a,b; }; int main() { vector vecC; //Populate vecC how do i now sort according to a or b?? do I pass in a function pointer to sort(.....)?? } You could overload the < operator for C class C { public: int a,b; bool operator < ( C c ) { return a < c.a; } } Jul 22 '05 #4

 P: n/a "llewelly" wrote in message struct compare { bool operator()(C const& lhs, C const& rhs){return lhs.a < rhs.a;} }; Typically it should be a const function. bool operator()(C const& lhs, C const& rhs) const {return lhs.a < rhs.a;} Jul 22 '05 #5

### This discussion thread is closed

Replies have been disabled for this discussion.