Sorting by class value

M

Michael

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
 
L

llewelly

Michael said:
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());
}
 
T

Thomas Matthews

Michael said:
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
 
J

joey tribbiani

Michael said:
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; }
}
 
S

Siemel Naran

llewelly said:
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;}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,919
Members
47,460
Latest member
eibafima

Latest Threads

Top