How to do this sorting of a list of class type?
Hi all,
I have got a list of class type that I need to do list.sort() on.
the class type is
Code:
class node_info{
public:
node_number;
node_gain;
}
And I have a list to store all these class types: list<node_info> node_list;
for example, initially the list of 3 elements would be like {{0,3},{1,2},{2,1}}
After the sort, i would like it to be like{{2,1},{1,2},{0,3}}
Could anyone tell me how to do this kind of trick? Would the time complexity be nlogn for this kind of sorting?
Thanks a lot:)
Re: How to do this sorting of a list of class type?
provide a less than operator for node_info's then use list::sort to sort them low to high and then list::reverse to sort them high to low, or alternatively write a comparison function and pass it in as an argument to list::sort. The function should compare two node_info's and return a bool.
Re: How to do this sorting of a list of class type?
Could you write a small example code showing me how to provide < operator for node_info?
Is that something called operator overload?
I will try to look up the book for that part.
Re: How to do this sorting of a list of class type?
Problem solved, thanks a lot.
I write my code like this.
Code:
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
class node_info{
friend bool operator<(const node_info&, const node_info&);
public:
int node_number;
int node_gain;
};
inline bool operator<(const node_info &lh, const node_info &rh){
if(lh.node_gain<rh.node_gain)
return 1;
else
return 0;
}
int main(){
list<node_info> gvec;
for(int i=0; i!=10; i++){
node_info temp;
int temp_gain;
temp.node_number=i;
cin>>temp_gain;
temp.node_gain=temp_gain;
gvec.push_back(temp);
}
for(list<node_info>::iterator iter=gvec.begin();iter!=gvec.end();iter++)
cout<<iter->node_number<<" "<<iter->node_gain<<endl;
cout<<endl;
gvec.sort();
//sort(gvec.begin(), gvec.end());
//list<node_info>::iterator iter=gvec.end();
//cout<<"AA "<<*(--iter);
for(list<node_info>::iterator iter=gvec.begin();iter!=gvec.end();iter++)
cout<<iter->node_number<<" "<<iter->node_gain<<endl;
cout<<"finished";
return 0;
}