How to sort a list with objects.

Sep 12, 2016 at 11:38pm
Hi guys, I have a problem, I wanted to sort the numbers of ingredients.
I tried several methods but have not reached a result. I've searched on the internet, I found an example, but I don't know how to make with "greater" like this "http://www.java2s.com/Tutorial/Cpp/0340__list/sortlistwithuserdefinedobjectswithgreater.htm" I don't get it... If someone can explain me with an easy path or method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 #include<iostream>
#include<list>
using namespace std;
class Milkshake{
private:
    string name;
    int ingredients;
public:
    Milkshake(string n="",int ing=0)
    {
        name=n;
        ingredients=ing;
    }
    void print()
    {
        cout<<"Name: "<<name<<endl;
        cout<<"ingredients: "<<ingredients<<endl;
    }
};
int main()
{
    Milkshake d1("Yas",40);
    Milkshake d2("Ord",2);
    Milkshake d3("Das",25);
    d1.print();
    list<Milkshake>myList;
    myList.push_front(d1);
    myList.push_front(d2);
    myList.push_front(d3)
    myList.sort();

}
Sep 13, 2016 at 3:41am
First you need to define what "sorting" means for your objects. Are you sorting alphabetically by 'name', or numerically by number of 'ingredients'.

Once you've decided that, you just need to make either a function or an overloaded parenthesis operator which implements your type of sort.

Take a look at this for some inspiration: http://www.cplusplus.com/reference/algorithm/sort/
Sep 13, 2016 at 6:30am
I want to do both, but first I want to do sorting of ingredients .
When you said an overloaded parenthesis operator you speak about that:
bool operator()( Milkshake &a)
{
return(ingredients>a.ingredients;
}
I tried something but doesn't work.
Last edited on Sep 13, 2016 at 7:00am
Sep 13, 2016 at 8:01am
I tried something but doesn't work.
The operator for sort() is this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Milkshake
{
...
public:
    bool operator<(const Milkshake &a) const
    {
      return (ingredients < a.ingredients); // (a.ingredients < ingredients)
    }
...
};

..

[EDIT]
std::sort(myList.begin(), myList.end());
// In case of list:
myList.sort();
Last edited on Sep 13, 2016 at 1:48pm
Sep 13, 2016 at 8:55am
TheSmallGuy, thank you man for your example, you are a savior of lives, now I have an idea how to do. Thank you all for help.
Sep 13, 2016 at 9:00am
But I have a question, can I ask you?
Sep 13, 2016 at 9:17am
I sent you a pm.
Last edited on Sep 13, 2016 at 9:18am
Sep 13, 2016 at 1:12pm
TheSmallGuy wrote:
P.S : std::list::sort() does not seem to be well supported by my compiler.

It is not your compiler. The std::sort requires random-access iterators. The std::list does not have them.
See http://www.cplusplus.com/reference/algorithm/sort/
Topic archived. No new replies allowed.