You are not logged in.

#1 2011-03-09 02:41:34

lamdacore
Member
Registered: 2009-11-05
Posts: 128

[SOLVED]C++ STL sort on a struct

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

#2 2011-03-09 03:16:55

tavianator
Member
From: Waterloo, ON, Canada
Registered: 2007-08-21
Posts: 859
Website

Re: [SOLVED]C++ STL sort on a struct

You declared comp_func as a method; you probably intended for it to be static.

Offline

#3 2011-03-09 03:40:19

lamdacore
Member
Registered: 2009-11-05
Posts: 128

Re: [SOLVED]C++ STL sort on a struct

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

#4 2011-03-09 03:52:09

tavianator
Member
From: Waterloo, ON, Canada
Registered: 2007-08-21
Posts: 859
Website

Re: [SOLVED]C++ STL sort on a struct

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

#5 2011-03-09 03:53:14

lamdacore
Member
Registered: 2009-11-05
Posts: 128

Re: [SOLVED]C++ STL sort on a struct

Thanks a lot.

cheers.

Offline

Board footer

Powered by FluxBB