Oleg Shirokikh Oleg Shirokikh - 2 months ago 5
C++ Question

Efficient way to check if a given string is equivalent to at least one string in the given set of strings

Given a set of strings, say

"String1", "String2",..., "StringN"
, what is the most efficient way in C++ to determine (return
true
or
false
) whether given
string s
matches any of the strings in the above set?

Can Boost.Regex be used for this task?

Answer

std::unordered_set would provide the most efficient look-up (amortized constant time).

#include <unordered_set>
#include <string>
#include <cassert>

int main() {
    std::unordered_set<std::string> s = {"Hello", "Goodbye", "Good morning"};
    assert(s.find("Goodbye") != s.end());
    assert(s.find("Good afternoon") == s.end());
    return 0;
}