Search code examples
c++boosthashmultimap

Pointer as key in multimap


Can I have a boost::multimap with a const char* as the key? Or any other pointer has the key?

I thought it was fine. But when I did that I could not find my values after insertion. But when I changed they key to a std::string it works fine. I didnt understand at first.

I thought about it, and this is what I think is the explanation.

When I have a char* as the key it would mean the value is mapped to some memory addresss' value like "0xccbbee" as the key(like key(0xccbbee)->value(1)). So to extract the value I would need to send in "0xccbbee" to get the value 1, which I wouldnt be doing.

I would instead try to get the value by using the key of what was there in the memory location(maybe it was "HELLO") and try to get the value mapped to "HELLO" and I would not get anything. Was that the problem?

Is my understanding correct. Please let me know if my understanding is right. I am trying to learn.

TIA

-R


Solution

  • Your explanation of the problem is correct. To achieve the desired result, configure the multimap with a proper Comparator:

    struct StrCompare
    {
        bool operator()(const char* lhs, const char* rhs) const
        {
            return strcmp(lhs, rhs) < 0;
        }
    };
    
    typedef boost::multimap<const char*, whatever, StrCompare> StrToWhateverMultimap;