Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
307 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...