从字符串列表中最快查找字符串

Bhu*_*ant 3 c++ stl data-structures c++11

我有一个字符串列表,我必须查找该列表中是否存在某个字符串。我想在低延迟定价引擎中使用逻辑,所以我想拥有真正快速的逻辑。我想到将这些字符串作为键存储在映射中,然后可以使用 find() 或 count() 函数进行相同的操作。任何人都可以建议任何其他更有效的逻辑吗?

Ali*_*Ali 5

可能std::unordered_set是适合您需求的选择。然后您可以用来find()检查字符串是否存在。就像这里的示例代码一样:

#include <iostream>
#include <string>
#include <unordered_set>

int main() {

  std::unordered_set<std::string> myset{ "red", "green", "blue" };

  std::cout << "color? ";
  std::string input;
  std::cin >> input;

  auto pos = myset.find(input);

  if (pos != myset.end())
    std::cout << *pos << " is in myset\n";
  else
    std::cout << "not found in myset\n";

}
Run Code Online (Sandbox Code Playgroud)

要了解如何std::unordered_set工作,请参阅哈希集