B
bb
#include <iostream>
#include <map>
using std::cout;
using std::endl;
using std::map;
using std:
air;
struct myType {
int m1_;
int m2_;
myType(int m1, int m2) : m1_(m1), m2_(m2) {}
myType(const myType& rhs) : m1_(rhs.m1_), m2_(rhs.m2_) {}
~myType() {}
bool operator<(const myType& rhs) const {
if ((this->m1_ < rhs.m1_) && (this->m2_ < rhs.m2_)) { return true; }
return false;
}
};
int main(int argc, char* argv[]) {
typedef map<myType, int> myMap;
myType ky1(2,3);
myType ky2(3,2);
myMap mymap;
mymap.insert(myMap::value_type(ky1,10));
cout << mymap.size() << endl;
mymap.insert(myMap::value_type(ky2,11)); // updates instead of
inserting a second entry
cout << mymap.size() << endl;
}
In the above code, the objects ky1 & ky2 are obviously not the same.
(at least i do not intend them to be so). However, per strict weak
ordering, stl does assume they are equivalent. Hence, even after the
second insert, mymap.size() returns 1.
Is my operator<() implementation is wrong?
What all should ensure when I use my own type as a key in an
associative container?
Thanks in advance.
#include <map>
using std::cout;
using std::endl;
using std::map;
using std:
struct myType {
int m1_;
int m2_;
myType(int m1, int m2) : m1_(m1), m2_(m2) {}
myType(const myType& rhs) : m1_(rhs.m1_), m2_(rhs.m2_) {}
~myType() {}
bool operator<(const myType& rhs) const {
if ((this->m1_ < rhs.m1_) && (this->m2_ < rhs.m2_)) { return true; }
return false;
}
};
int main(int argc, char* argv[]) {
typedef map<myType, int> myMap;
myType ky1(2,3);
myType ky2(3,2);
myMap mymap;
mymap.insert(myMap::value_type(ky1,10));
cout << mymap.size() << endl;
mymap.insert(myMap::value_type(ky2,11)); // updates instead of
inserting a second entry
cout << mymap.size() << endl;
}
In the above code, the objects ky1 & ky2 are obviously not the same.
(at least i do not intend them to be so). However, per strict weak
ordering, stl does assume they are equivalent. Hence, even after the
second insert, mymap.size() returns 1.
Is my operator<() implementation is wrong?
What all should ensure when I use my own type as a key in an
associative container?
Thanks in advance.