简体   繁体   中英

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

I want to be able to check if the string std::string x is equal to any value in string array std::string y[N] . I know how to do this by using a for loop and using an if statement, but is there an even faster way that I could do this? Is there a built in function in c++ that can do this?

The built-in container for that is std::unordered_set<std::string>

Replace your string array with that unordered_set , and the checks will become much faster:

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

Presuming you use STL classes, there's a few mechanisms you can use, depending on the domain of your problem.

For example, if the array is unsorted, then it doesn't really matter: there are StdLib algorithms which will better convey intent and shrink the code, but they'll be performance-wise equivalent to a simple for-loop. This code is identical, performance-wise, to a simple for-loop.

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;

If the collection is sorted, you can use a Binary Search, which dramatically improves performance:

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;

If you don't need duplicate strings in your collection, you can use a set or unordered_set to collect the strings, which will guarantee at least the performance of a binary-search, and if you use unordered_set instead, could be faster.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM