Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a string is present as an element in a vector

Tags:

c++

vector

What's the most efficient way to check whether an stl vector of strings contains a specific string?

like image 770
user620189 Avatar asked Mar 30 '11 17:03

user620189


1 Answers

The obvious yet possibly too-slow solution is std::find(vec.begin(), vec.end(), your_string);

If your vector isn't changing much, sort it first, then use binary_search, lower_bound, upper_bound, or equal_range. If your vector changes a lot, consider using a set/multiset (or if needed map/multimap) instead.

Depending on your needs a hash (unordered_set) might be appropriate as well, but it's more different from your initial container choice than normal ordered containers, and not supplied prior to C++0x (you can get it from boost easily).

like image 72
Mark B Avatar answered Oct 13 '22 14:10

Mark B