You are not logged in.
Pages: 1
I am trying to sort a vector of a struct in the following code. The struct has 2 string data member. I made a custom comparison function and trying to sort a vector of the struct. This however does not work.
I am using this as reference: http://www.cplusplus.com/reference/algorithm/sort/
I will appreciate any help/pointers.
Thanks.
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
class AAA{
public:
void add();
void out();
void resort();
private:
struct str{
string key;
string item;
};
bool comp_func(str& a, str& b);
vector<str> m_data;
};
void AAA::add(){
for(char i='z';i>='n';i--){
str k;
k.item=i+1;
k.key=i;
m_data.push_back(k);
}
}
bool AAA::comp_func(str& a, str& b){ //custom comparison function
return a.key>b.key;
}
void AAA::resort(){ //sorting fuction
sort(m_data.begin(),m_data.end(),comp_func);
}
void AAA::out(){
for(vector<str>::iterator it=m_data.begin();it!=m_data.end();it++){
cout<<it->key<<"|"<<it->item<<endl;
}
}
int main(){
AAA obj;
obj.add();
obj.out();
obj.resort();
obj.out();
cin.ignore(10000,'\n');
return(1);
}
Last edited by lamdacore (2011-03-09 03:40:38)
Offline
You declared comp_func as a method; you probably intended for it to be static.
Offline
Thanks.
Doing this works- and sorts the vector.
static bool comp_func(str& a, str& b);
I don't quite understand why this needs to be done. Can someone explain the theory behind this please?
Also, something similar can be used for list::sort?
Last edited by lamdacore (2011-03-09 03:41:05)
Offline
Yep, that function should work fine for list::sort.
The difference between static and non-static member functions is this: a static one can be called without an object, like "AAA::comp_func(a, b);" while a non-static member requires an object, like this: "AAA aaa; aaa.comp_func(a, b);"
Offline
Thanks a lot.
cheers.
Offline
Pages: 1