HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMajor

contains() algorithm for std::vector

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
stdalgorithmcontainsforvector

Problem

I wrote the following function for the purpose of reusability:

template
bool contains(vector 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?

Solution

template
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 

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

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

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

Code Snippets

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);
}
#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); }

Context

StackExchange Code Review Q#59997, answer score: 35

Revisions (0)

No revisions yet.