sort alphabetically

Hi everybody. I have a problem with sort alphabetically. I have a list of stuctures and I don't know how to sort it. I know how to sort list with function iter_swap but how to sort lsit of structures accordingly to one member. For example alphabetically or by bigger member(int).

Please, just tell a function and i will find out rest by myself.
http://en.cppreference.com/w/cpp/container/list/sort
You should write your own comparator function. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <list>

struct foo
{
    int bar;
    foo(int x) :bar(x) {};
};

bool isLess(foo &left, foo &right)
{
    return left.bar < right.bar;
}

int main()
{
    std::list<foo> list = { 8,7,5,9,56,1,3,2,6,4 };
    list.sort(isLess);
    std::cout << (list.begin() -> bar) ;
}

Last edited on
I'm sorry I haven't understood. When I have a structure and want to sort it for example by Id
1
2
3
4
5
6
struct sWorker
{
    string Name;
    char Id;
    double avr_sal;
};


1
2
3
4
5
6
7
8
9
10
bool isIdLess(sWorker &left, sWorker &right)
{
    return left.Id < right.Id;
}

//...
//Supposing you have std::list<sWorker> workers;
//somewhere
workers.sort(isIdLess);
//Now your workers list sorted by id. 


If you want sort workers with same Id by salary, you can write another comparator function:
1
2
3
4
5
6
7
bool sortIdSal(sWorker &left, sWorker &right)
{
    if(!(left.Id == right.Id))
        return left.Id < right.Id;
    else
        return left.avr_sal < right.avr_sal
}

and use it like:workers.sort(sortIdSal);

Also you can define operator<(sWorker &left, sWorker &right) and you can use sort like workers.sort() and almost all standart algorithms (iter_swap...) will work
Last edited on
Thanks MiiNiPaa! It works
Topic archived. No new replies allowed.