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

时间:2017-09-26 20:54:04

标签: c++ arrays string

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

2 个答案:

答案 0 :(得分:1)

内置容器为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();
}

答案 1 :(得分:1)

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

例如,如果数组未排序,那么它并不重要:有StdLib算法可以更好地传达意图并缩小代码,但它们在性能方面与简单相当for循环。这个代码在性能方面与简单的for循环完全相同。

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;