Is it possible to map string to int faster than using hashmap?

前端 未结 7 1282
温柔的废话
温柔的废话 2020-12-08 19:52

I understand that I should not optimize every single spot of my program so please consider this question to be \"academic\"

I have maximum 100 strings and integer n

7条回答
  •  长情又很酷
    2020-12-08 20:22

    Small addition to sehe’s post:

    If you use a simple std::map the net effect is prefix search (because lexicographical string comparison shortcuts on the first character mismatch). The same thing goes for binary search in a sorted container.

    You can harness the prefix search to be much more efficient. The problem with both std::map and naive binary search is that they will read the same prefix redundantly for each individual comparison, making the overall search O(m log n) where m is the length of the search string.

    This is the reason why a hashmap outcompetes these two methods for large sets. However, there is a data structure which does not perform redundant prefix comparisons, and in fact needs to compare each prefix exactly once: a prefix (search) tree, more commonly known as trie, and looking up a single string of length m is feasible in O(m), the same asymptotic runtime you get for a hash table with perfect hashing.

    Whether a trie or a (direct lookup) hash table with perfect hashing is more efficient for your purpose is a question of profiling.

提交回复
热议问题