Possible Duplicate:
What requirements must std::map key classes meet to be valid keys?
I want to use std::map as map from my class to another one. If I try the following code, I get an error “undefined operator <“. Does it mean that I need an ordering on class K to use map? And does it have to be full ordering? And do I need all four ordering operators or > is enough?
#include <iostream>
#include <map>
#include <stdio.h>
using namespace std;
struct K {
int i, j;
K(int i, int j) : i(i), j(j){}
friend bool operator==(const K& x, const K& y){ return (x.i==y.i)&&(x.j==y.j); }
friend bool operator!=(const K& x, const K& y){ return !(x==y); }
/* friend bool operator<(const K&x, const K&y){
if(x.i<y.i) return true;
if(x.i>y.i) return false;
return x.j<y.j;
}
friend bool operator>(const K&x, const K&y){ return y<x; }
friend bool operator<=(const K&x, const K&y){ return !(y<x); }
friend bool operator>=(const K&x, const K&y){ return !(x<y); }
*/
};
int main(){
map<K, float> m;
m[K(1,2)]=5.4;
if(m.find(K(1,2))!=m.end())
cout << "Found: " << m[K(1,2)] << endl;
else
cout << "Not found" << endl;
return 0;
}
Yes, you need a way to compare elements (
operator<) in order to use the std::map. One of the features of map is that it keeps its contents in sorted order, but to achieve this its need to know how to compare items.You have three options to implement a comparison method:
operator<definition in KMake a
compfunctor that know to how to compare two K elements and add this as a template parametermap<K, float, comp> m;You can define the std::less specialization for K
And simple use
map<K, float> m;This works because by the template definition for map has the compare function set to std::less.