Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting vector of pointers

Tags:

I'm having a little trouble trying to sort a vector of pointers.

This is what I have done so far:

class Node
{
    private:
    vector <Node*> _children;
    string _data;
    ...
    public:
    void Node::add_child(Node* child)
    {
        ...
        sort(_children.begin(), _children.end());
    }

    bool Node::operator<(const Node& node)
    {
        return (this->_data.compare(node._data) == -1);
    }
};

My less-than operator works, if I write like this:

Node* root = new Node("abc");
Node* n = new Node("def");
cout << (*root<*n) << endl;

Why does sort never call the operator?? Any help would be appreciated! Thanks.

madshov

like image 341
madshov Avatar asked Sep 16 '11 15:09

madshov


1 Answers

Because you sort the pointer values, not the Nodes they point to.

You can use the third argument of the std::sort algorithm to specify a custom comparator.

For example :

bool comparePtrToNode(Node* a, Node* b) { return (*a < *b); }

std::sort(_children.begin(), _children.end(), comparePtrToNode);

(note that this code is just an indication - you'll have to add extra safety checks where needed)

like image 148
Sander De Dycker Avatar answered Sep 21 '22 11:09

Sander De Dycker