Thomas
Thomas

Reputation: 13

set<class> insert problem

why is the following programm not working? How can i fix it?

#include <iostream>
#include <set>

using namespace std;

class K {

private:
    long a;
};

int main ()
{   
    K a;
    set<K> b;

    b.insert(a);

    return 0;
}

Upvotes: 1

Views: 1250

Answers (2)

Yurie
Yurie

Reputation: 899

set requires your class to have operator< defined. For example:

class K {
public:

bool operator< (const K& other) const {
    return this->a < other.a;
}

private:

long a;

};

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 545568

std::set requires a sorting of the elements. It requires that you can compare its elements according to some ordering.

Either add an operator < for your class K or provide the second template argument – the comparer – to the set class that determines the ordering between two K instances.

Overloading the operator < is straightforward:

bool operator <(K const& x, K const& y) {
     return x.a < y.a;
}

This will mean that one instance of K is less than another if and only if its member a is less than the other’s.

Upvotes: 6

Related Questions