1

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?

Pilpel
  • 2,931
  • 3
  • 25
  • 57

1 Answers1

3

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 Nodes 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; }
);
Barry
  • 247,587
  • 26
  • 487
  • 819
  • Thanks! But just for learning purposes, say this was an std::vector, and I must use pointers to objects, what would be the solution to that? – Pilpel Apr 19 '15 at 21:30
  • @Pilpel Updated my answer to illustrate that. – Barry Apr 19 '15 at 21:34
  • Never seen that `[] (...) {...}` syntax before. What does it do? Does it create a function inside min_element()? – Pilpel Apr 19 '15 at 21:39