简体   繁体   中英

std::min_element returning unexpected result from class objects

I use std::min_element on this Node object I created that has an index. I have a std::set container that holds 10 Nodes with different indices, and then I call std::min_element to get the Node with the lowest index number.

#include <iostream>
#include <string>
#include <algorithm>
#include <set>

using namespace std;

class Node
{
public:
    Node(int index) : _index(index) {}

    int index() const { return _index; }

    inline bool operator< (const Node &right) { return this->index() < right.index(); }

private:
    int _index;
};

int main()
{
    set<Node*> s;

    for(int i = 10; i > 0; i--) //10 , 9 , 8 ...
        s.insert(new Node(i));

    Node *lowest = *min_element(s.begin(), s.end());
    cout << lowest->index() << endl;

    //free
    for(set<Node*>::iterator iter = s.begin(); iter != s.end(); iter++)
        delete *iter;

    system("pause");
    return 0;
}

The output is 10 but sure be 1 . What am I doing wrong?

You have a set<Node*> , not a set<Node> . So it's using the standard pointer operator< , not the one that you defined. If you change your type to be set<Node> and add your Node s in by value, everything will work just fine.

Also note that set<T> is already sorted by operator< , so if you had:

std::set<Node> nodes;
// add nodes here
Node& lowest = *nodes.begin();

You don't have to use min_element . That algorithm would be more useful if you were searching in a vector :

std::vector<Node*> nodes;
// add nodes here
auto it = std::min_element(std::begin(nodes), std::end(nodes),
    [](Node* a, Node* b){ return *a < *b; }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM