ruby86123
ruby86123

Reputation: 1

How can I create own string compare object for C++ map

I need a map of key to regard '-' as '1' or '0'.

For example :

The map<string, int> already has an element <"1-1", 1>. When I use map.find("101"), I should get <"1-1", 1>.

This is my function

struct keycompare
{
    bool operator()(const std::string& x, const std::string& y)
    {
        int len = x.length();
        for(int i=0;i<len;i++){
            if(x[i]==y[i])continue;
            else if( x[i]=='-'  || y[i]=='-')continue;
            else return x[i]<y[i];
        }
        return false;
    }
};

It will go wrong in some cases when I use map.find(). Is there any good way to debug it?

Upvotes: 0

Views: 49

Answers (1)

Caleth
Caleth

Reputation: 62636

You can't use such a comparison with std::map.

One of the requirements of the Compare template member is the transitivity of the equivalence relation !comp(a, b) && !comp(b, a). Your compare does not hold, e.g. in the case

keycompare comp;

auto equiv = [comp](auto l, auto r) { return !comp(l, r) && !comp(r, l); };

std::string a("111");
std::string b("1-1");
std::string c("101");

std::cout << std::boolalpha << "a == b " << equiv(a, b) << std::endl;
std::cout << std::boolalpha << "b == c " << equiv(b, c) << std::endl;
std::cout << std::boolalpha << "a == c " << equiv(a, c) << std::endl;

Specifically, if your map contains both "111" and "101", which should be found with a search for "1-1"?

Upvotes: 2

Related Questions