Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 342
Oleg Shirokikh Avatar asked Dec 02 '22 17:12

Oleg Shirokikh


2 Answers

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;
}
like image 72
Joseph Mansfield Avatar answered Dec 20 '22 17:12

Joseph Mansfield


You can put all your strings in a std::set and then check if that string is in the set.

like image 44
Caesar Avatar answered Dec 20 '22 15:12

Caesar