how to overload < for std::sort

Hi Everyone

Say I have a class

public A{

A(std::string name);
std::string name;

bool operator < (const A *(&right));
}

int main()
{
A *a = new A("a");
A *b = new A("b");

std::list<A*> list.push_back(a);
list.push_back(b);

list.sort();

}

And here is my question how come my overload operator < didn't get called?

Last edited on
Well, for once what you post is not valid C++. Why don't you copy and paste from your source code instead?

Second, if that's your signature for operator<(), then that is most likely the reason. The operator<() used by sort is bool operator<(const A&) const;.

So double check your operator's prototype, but above all, you should have posted valid C++ in the first place. Now we are unsure if what you show reflects your problem accurately enough or not.
Normally, containers are not used with pointers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <string>
#include <list>
#include <iostream>
struct A {
    std::string name;
    A(const std::string& name) : name(name) {}
    bool operator< (const A& right) const { return name < right.name; }
};

int main()
{
    std::list<A> list = {A("c"), A("a"), A("b")};
    list.sort();

    for(auto a : list)
        std::cout << a.name << '\n';
}

demo: http://ideone.com/tOHqc

If you were trying to create an operator< for pointers, it's not allowed by the language. What is allowed, is a functor for comparison:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <string>
#include <list>
#include <iostream>
struct A {
    std::string name;
    A(const std::string& name) : name(name) {}
};

struct pA_comp {
    bool operator() (const A* left, const A* right) const { 
       return left->name < right->name;
    }
};
int main()
{
    std::list<A*> list = {new A("c"), new A("a"), new A("b")};
    list.sort(pA_comp());

    for(auto a : list)
    {
        std::cout << a->name << '\n';
        delete a;
    }
}

demo: http://ideone.com/zJ2ca
Thanks Cubbi those were really good responds and functor is what I need in this case.

Cheers
Topic archived. No new replies allowed.