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

前端 未结 7 1253
温柔的废话
温柔的废话 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:25

    If the strings are known at compile-time you can just use an enumeration:

    enum
    {
      Str1,
      Str2
    };
    
    const char *Strings = {
      "Str1",
      "Str2"
    };
    

    Using some macro tricks you can remove the redundancy of re-creating the table in two locations (using file inclusion and #undef).

    Then lookup can be achieved as fast as indexing an array:

    const char *string = Strings[Str1]; // set to "Str1"
    

    This would have optimal lookup time and locality of reference.

提交回复
热议问题