In this article we will different ways to find an element in vector and get its index.

Suppose we have a vector of int i.e.

Now we want to find if number 22 exists in vector ? If yes then what’s its index or position in the vector ?

std::vector doesn’t provides any direct function to check if an element exists in vector or not. So let’s see how to do that using STL Algorithms.

Finding an element in vector using STL Algorithm std::find()

Basically we need to iterate over all the elements of vector and check if given elements exists or not.
This can be done in a single line using std::find i.e.

It accepts a range and an element to search in the given range. If element is found then it returns an iterator to the first element in the given range that’s equal to given element, else it returns an end of the list.

If element is found then we can get its index from the iterator i.e.

But in practical, we will not have vector of integers always. So, let’s create a generic function for this.

Generic function to find an element in vector of any type

Let’s create a generic function to search an element in any type of vector i.e.

This function tells if given element exists in vector and if yes then it also return its position in the vector.

Let’s use this function to find an element in vector i.e.

Finding an element by custom comparator using std::find_if()

Instead of directly searching by value in the vector , we can search by custom logic too.

Like, in a vector of int check if any multiple of 3 exists i.e.

Finding an element in vector using C++11 Range Based for loop

We can also iterate over the vector using range based for loop and check if element exists or not.

Complete example is as follows,


Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.