How can I increase the performance in a map lookup with key type std::string?

后端 未结 14 1225
天涯浪人
天涯浪人 2021-02-05 23:25

I\'m using a std::map (VC++ implementation) and it\'s a little slow for lookups via the map\'s find method.

The key type is std::string.

14条回答
  •  轮回少年
    2021-02-05 23:57

    As Even said the operator used in a set is < not ==.

    If you don't care about the order of the strings in your set you can pass the set a custom comparator that performs better than the regular less-than.

    For example if a lot of your strings have similar prefixes (but they vary in length) you can sort by string length (since string.length is constant speed).

    If you do so beware a common mistake:

    struct comp {
        bool operator()(const std::string& lhs, const std::string& rhs)
        {
            if (lhs.length() < rhs.length())
                return true;
            return lhs < rhs;
        }
    };
    

    This operator does not maintain a strict weak ordering, as it can treat two strings as each less than the other.

    string a = "z";
    string b = "aa";
    

    Follow the logic and you'll see that comp(a, b) == true and comp(b, a) == true.

    The correct implementation is:

    struct comp {
        bool operator()(const std::string& lhs, const std::string& rhs)
        {
            if (lhs.length() != rhs.length())
                return lhs.length() < rhs.length();
            return lhs < rhs;
        }
    };
    

提交回复
热议问题