C++ Notes

zurück/back to home

contains() for STL containers

Checking whether an element is in a Python container is simple:

my_set = set([1, 2, 3])
if 4 in my_set:
  print "4 is in my_set!"

In C++, we have to use find() and end():

int arr[] = {1, 2, 3};
std::tr1::unordered_set<int> my_set(arr, arr + 3);
if my_set.find(4) != my_set.end()
  printf("4 is in my_set\n");

The following is a small helper function that (hopefully) reduces some syntactic noise:

template <typename C, typename T>
bool contains(const C &amp;c, const T &amp;x)
{ return c.find(x) != c.end(); }

Now, we can do this:

int arr[] = {1, 2, 3};
std::tr1::unordered_set<int> my_set(arr, arr + 3);
if contains(my_set, 4);
  printf("4 is in my_set\n");