# Check if the vector contains the given element or not in C++.

posted Aug 4

Vectors are a good replacement over arrays if we want dynamic memory allocation. As usual, vectors contain elements as content. So in this article I’ll discuss different methods to check if a vector contains a given element or not.

# Methods

1. Std::count

2. Std::find

3. Std::find_if

4. Binary search

### Std::count

The easiest way to check is to count the number of the vectors having specified value. We will get our element if count is non zero.

``````#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
std::vector<int> v = { 4, 7, 5, 2, 6, 9 };
int key = 6;

if (std::count(v.begin(), v.end(), key))
std::cout << "Element found";
else

return 0;
}``````

### Std::find

The more organized solution is to use std::find to find the value of a given range. Std::find is an algorithm present in <algorithm> header file. Std::find has more advantage over std::count because it is fast since find() stops as soon as it finds the element whereas count() traverses over the whole container.

``````#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
std::vector<int> v = { 4, 7, 5, 2, 6, 9 };
int key = 6;

if (std::find(v.begin(), v.end(), key) != v.end())
std::cout << "Element found";
else

return 0;
}``````

### Std::find_if

As the name suggests it has some kind of conditions to satisfy. It requires a predicate. A predicate is a C++ function returning a boolean or an object having a bool operator() member. A unary predicate takes one argument, a binary takes two, and so on.

``````#include <iostream>
#include <vector>
#include <algorithm>

struct compare
{
int key;
compare(int const &i): key(i) { }

bool operator()(int const &i)
{
return (i == key);
}
};

int main()
{
std::vector<int> v = { 4, 7, 5, 2, 6, 9 };
int key = 6;

if (std::find_if(v.begin(), v.end(), compare(key)) != v.end())
std::cout << "Element found";
else

return 0;
}``````

### Binary search

This algorithm follows more of the mathematics thing to find the element in the vector. It will return true if an element is found otherwise false but only if the vector is ordered.

``````#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7 };
int key = 6;

if (std::binary_search(v.begin(), v.end(), key))
std::cout << "Element found";
else