user620189
user620189

Reputation: 2693

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

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

Upvotes: 11

Views: 34716

Answers (5)

davidhigh
davidhigh

Reputation: 15528

Here is a C++11 alternative:

#include<functional>
#include<vector>
#include<string>

std::vector<std::string> v;
bool elementFound = std::any_of(v.begin(), v.end(), [](std::string const& s) {return s=="string-to-search";});

Feel free to adjust the lambda function to what you want, e.g.

[](std::string const& s) {return s.size()>3;}

Upvotes: 4

Mark B
Mark B

Reputation: 96311

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).

Upvotes: 20

quamrana
quamrana

Reputation: 39414

Use std::find to find the target string. This is a linear search, so beware searching large vectors.

To find out if the vector contains the target or not, use:

bool isPresent = (std::find(vec.begin(), vec.end(), target) != vec.end());

Upvotes: 10

jmccarthy
jmccarthy

Reputation: 480

vector<string> v;
vector<string>::iterator it;
it = std::find(v.begin(), v.end(), "stringToFind");

Upvotes: 3

Mahesh
Mahesh

Reputation: 34665

Use std::find to find the string.

std::find(stringVector.begin(), stringVector.end(), "specificStringToFind") ;

Upvotes: 0

Related Questions