template<class C, class T>
auto contains(const C& v, const T& x)
-> 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 <algorithm>
template<class C, class T>
inline auto contains_impl(const C& c, const T& x, int)
-> decltype(c.find(x), true)
{ return end(c) != c.find(x); }
template<class C, class T>
inline bool contains_impl(const C& v, const T& x, long)
{ return end(v) != std::find(begin(v), end(v), x); }
template<class C, class T>
auto contains(const C& c, const T& x)
-> decltype(end(c), true)
{ return contains_impl(c, x, 0); }
return find(v.begin(), v.end(), x) != v.end();
. I would pass the parameters byconst
reference too. You don't need copies. – juanchopanza Aug 10 '14 at 8:23contains
function here can't be too generic for eachSTL Container
since the arguments tofind
algorithm varies differently. – Krishna_Oza Oct 29 '15 at 10:34