Given a vector in C++, check if it contains a specified element or not.

Searching for an element in a vector is a linear-time operation unless the vector is sorted. The <algorithm> header offers many functions that we can use for searching:

1. Using std::count function

The simplest solution is to count the total number of elements in the vector having the specified value. If the count is nonzero, we have found our element. This can be easily done using the std::count function.

Download  Run Code

2. Using std::find function

An efficient solution is to use the std::find algorithm to find a value in the given range. This performs faster than the std::count since count() traverses the whole container to get the element count while find() stops searching as soon as a matching element is found.

Download  Run Code

3. Using std::find_if function

We can also use the std::find_if algorithm, which requires a predicate. This is the recommended approach if the search needs to satisfy certain conditions. For example, we’re asked to find the first prime in a vector of integers or find the first string ending at some character in a vector of strings.

Download  Run Code

4. Using std::any_of function

This works similarly to the std::find_if algorithm. Instead of returning the iterator pointing to the first element in the sequence that satisfies a predicate, it returns a boolean value true if the predicate returns true for any of the elements and false otherwise.

Download  Run Code

5. Using std::none_of function

The std::none_of algorithm is just the opposite of std::any_of, i.e., it returns true if the predicate returns false for all the elements in the given range and returns false if the predicate returns true for at least one element.

Download  Run Code

Finally, if the vector is ordered, consider using std::binary_search algorithm that returns true if the element is found in the given range, and false otherwise. Binary Search procedure runs in O(log(n)) time.

Download  Run Code

That’s all about determining whether a vector contains a given element or not in C++.