By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,159 Members | 938 Online
Bytes IT Community
+ Ask a Question
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 <vector>
using std::vector;

class C
{
public:
int a,b;
};

int main()
{

vector<C> 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
Share this Question
Share on Google+
4 Replies


P: n/a
"Michael" <sl***********@hotmail.com> 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 <vector>
#include <algorithm>
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<C> 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 <vector>
using std::vector;

class C
{
public:
int a,b;
};

int main()
{

vector<C> 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 <vector>
using std::vector;

class C
{
public:
int a,b;
};

int main()
{

vector<C> 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" <ll*********@xmission.dot.com> 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.