contains() algorithm for std::vector I wrote the following function for the purpose of reusability:

template&lt;typename T&gt;
bool contains(vector&lt;T&gt; v, T x)
{
      if (v.empty())
           return false;
      if (find(v.begin(), v.end(), x) != v.end())
           return true;
      else
           return false;
}


Is this the correct way to do, oor is there any better (or more efficient) way?
template&lt;class C, class T&gt;
auto contains(const C&amp; v, const T&amp; x)
-&gt; decltype(end(v), true)
{
    return end(v) != std::find(begin(v), end(v), x);
}


Changes:


Removed the superfluous check for emptyness.
Parameterized on the container too, so all containers possible.

Removed from consideration if v is not a container of some sort.

Return the condition directly, no need for sticking it into a condition.


Of course, if you do many containment-tests on big containers, using an optimized container with optimized algorithms instead of vector might be a good idea, though measure it.

A bit more complicated, but using the container-provided find() for best performance where applicable:

#include &lt;algorithm&gt;

template&lt;class C, class T&gt;
inline auto contains_impl(const C&amp; c, const T&amp; x, int)
-&gt; decltype(c.find(x), true)
{ return end(c) != c.find(x); }

template&lt;class C, class T&gt;
inline bool contains_impl(const C&amp; v, const T&amp; x, long)
{ return end(v) != std::find(begin(v), end(v), x); }

template&lt;class C, class T&gt;
auto contains(const C&amp; c, const T&amp; x)
-&gt; decltype(end(c), true)
{ return contains_impl(c, x, 0); }