Cost of using std::map with std::string keys vs int keys?

前端 未结 6 1646
礼貌的吻别
礼貌的吻别 2020-12-06 01:43

I know that the individual map queries take a maximum of log(N) time. However I was wondering, I have seen a lot of examples that use strings as map keys. What is the perfor

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 02:09

    First of all, I doubt that in a real application, whether you have string keys or int keys makes any noticeable difference. Profiling your application will tell you if it matters.

    If it does matter, you could change your key to be something like this (untested):

    class Key {
    public:
        unsigned hash;
        std::string s;
    
        int cmp(const Key& other) {
            int diff = hash - other.hash;
            if (diff == 0)
                diff = strcmp(s, other.s);
            return diff;
    }
    

    Now you're doing an int comparison on the hashes of two strings. If the hashes are different, the strings are certainly different. If the hashes are the same, you still have to compare the strings because of the Pigeonhole Principle.

提交回复
热议问题