什么是最快检查字符串数组中是否存在字符串的方法

What is the fastest way to check if a string is present in a string array?

本文关键字:字符串 是否 存在 方法 数组 检查 什么      更新时间:2023-10-16

我希望能够检查字符串std::string x是否等于字符串数组std::string y[N]中的任何值。我知道如何使用for循环并使用if语句来执行此操作,但是我可以做到这一点更快吗?C 中是否有内置功能可以执行此操作?

假定您使用stl类,可以使用一些机制,具体取决于问题的域。

例如,如果阵列未排序,那么这并不重要:有一些stdlib算法可以更好地传达意图并收缩代码,但是它们的性能将等同于一个简单的前面循环。此代码在性能方面与简单的循环相同。

std::vector<std::string> strings = /*...*/;
//This will find the first string that matches the provided value and return its iterator
auto found_string_iterator = std::find(strings.begin(), strings.end(), "Desired String");
if(found_string_iterator != strings.end()) //found it
    std::cout << *found_string_iterator << std::endl;
else //Did not find it
    std::cout << "No such string found." << std::endl;

如果分类集合,则可以使用二进制搜索,从而极大地改善了性能:

std::vector<std::string> sorted_strings = /*...*/;
//In a sorted collection, this returns iterators to all strings matching the provided value
auto string_range_iterators = std::equal_range(strings.begin(), strings.end(), "Desired String");
if(string_range_iterators.first != strings.end()) {
    for ( auto i = string_range_iterators.first; i != string_range_iterators.second; ++i )
        std::cout << *i << std::endl;
} else {
    std::cout << "No Strings found." << std::endl;

如果您不需要集合中的重复字符串,则可以使用setunordered_set来收集字符串,这至少可以保证二进制搜索的性能,如果您使用unordered_set,则可以更快地。

std::set<std::string> collected_strings = /*...*/;
auto found_string_iterator = collected_strings.find("Desired String");
if(found_string_iterator != strings.end()) //found it
    std::cout << *found_string_iterator << std::endl;
else //Did not find it
    std::cout << "No such string found." << std::endl;

内置容器是 std::unordered_set<std::string>

用该unordered_set替换字符串数组,并且检查将变得更快:

bool contains( const std::unordered_set<std::string>& set, const std::string& s )
{
    return set.find( s ) != set.end();
}