-1

First of all, I defined my own memory allocator, MyAllocator. Then I define my own map based on std::map with my own memory allocator:

template <typename K, typename V, typename Comparator = std::less<K>>
using MyMap = std::map<K, V, Comparator, MyAllocatorAdapter<std::pair<const K, V>>>;

So the usage will be:

MyMap<std::string, float> my_map(std::less<std::string>(), allocator);

my_map["key1"] = 10.1
my_map["key2"] = 10.2
my_map["key3"] = 10.3

Here MyMap works perfectly, [], inline functions, iterator, etc, just like std::map. Good!

Then I define my own type, MyString, which also works perfectly.

class MyString{
  ...define operators[], =, !=, find(),substr(), etc
}

But when I use it as the key in MyMap, come with problems!

MyMap<MyString, float> my_map(std::less<MyString>(), allocator);
MyString my_string="key1";

Most functions like [], functions, iterator fails!

I debug into the program and found in

`/user/include/c++/4.8/bits/stl_mpl.h`, 

iterator doesn't move. Notice that std::less<> will eventually call MyString operator !=, I'd implement this function and no problem with that. I was stuck and debug the problem for 2 days! Need help! thanks!

Harvey Dent
  • 327
  • 2
  • 14

1 Answers1

4

std::less calls operator<. You need to implement that.

milleniumbug
  • 15,379
  • 3
  • 47
  • 71
  • Sorry to mis-described in my original post, I'd implemented MyString's operator <, which actually call != – Harvey Dent May 02 '15 at 00:07
  • @MartinGGWW That's bad, such `operator<` must abide by the rules of [strict weak order](https://en.wikipedia.org/wiki/Strict_weak_ordering) - which your operator fails to provide (for example, if `a < b` is true, then `b < a` must be false). – milleniumbug May 02 '15 at 00:34