Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast string search?

I have a vector of strings and have to check if each element in vector is present in a given list of 5000 words. Besides the mundane method of two nested loops, is there any faster way to do this in C++?

like image 833
ofey Avatar asked Feb 05 '13 21:02

ofey


1 Answers

You should put the list of strings into an std::set. It's a data structure optimized for searching. Finding if a given element is in the set or not is an operation which is much faster than iterating all entries.

When you are already using C++11, you can also use the std::unordered_set which is even faster for lookup, because it's implemented as a hash table.

Should this be for school/university: Be prepared to explain how these data structures manage to be faster. When your instructor asks you to explain why you used them, "some guys on the internet told me" is unlikely to earn you a sticker in the class book.

like image 54
Philipp Avatar answered Sep 30 '22 01:09

Philipp