JDiMatteo JDiMatteo - 2 years ago 80
C++ Question

C++ concisely checking if item in STL container (e.g. vector)

bool xInItems = std::find(items.begin(), items.end(), x) != items.end();

Is there a more concise way of checking if x is in items? This seems unnecessarily verbose (repeating items three times), which makes the intent of the code a little harder to read.

For example, is there something like the following:

bool xInItems = boost::contains(items, x);

If there doesn't exist any more concise boost/stl algorithm to check if a collection contains an item, is it considered good or bad practice to use instead a helper function to enable
contains(items, x)

Am I using the wrong STL container? Even a std::set would result in
bool xInItems = items.find(x) != items.end();
which still seems verbose. Am I thinking about this the wrong way?

Answer Source

If your data is sorted, you can use std::binary_search, which returns a bool:

bool xInItems = std::binary_search(items.begin(), items.end(), x));

If you really need to leave the items un-sorted, but have C++11 available, you could use std::any_of, but it requires a predicate, so it's likely to end up at least as verbose as std::find (and probably more so).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download