vendredi 1 mai 2015

C++ std_map doesn't iterate self-defined datatype

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!

Aucun commentaire:

Enregistrer un commentaire