C++ : How to find an element in vector and get its index ?

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.

std::vector<int> vecOfNums = { 12, 45, 54, 33, 2, 7, 8, 22, 43, 19 };

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.

// Check if element 22 exists in vector
std::vector<int>::iterator it = std::find(vecOfNums.begin(), vecOfNums.end(), 22);

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 (it != vecOfNums.end())
	std::cout << "Element Found" << std::endl;
else
	std::cout << "Element Not Found" << std::endl;

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

// Get index of element from iterator
int index = std::distance(vecOfNums.begin(), it);

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.

/*
Generic function to find an element in vector and also its position.
It returns a pair of bool & int i.e.

bool : Represents if element is present in vector or not.
int : Represents the index of element in vector if its found else -1

*/
template < typename T>
std::pair<bool, int > findInVector(const std::vector<T>  & vecOfElements, const T  & element)
{
	std::pair<bool, int > result;

	// Find given element in vector
	auto it = std::find(vecOfElements.begin(), vecOfElements.end(), element);

	if (it != vecOfElements.end())
	{
		result.second = distance(vecOfElements.begin(), it);
		result.first = true;
	}
	else
	{
		result.first = false;
		result.second = -1;
	}

	return result;
}

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.

std::pair<bool, int> result = findInVector<int>(vecOfNums, 45);

if (result.first)
	std::cout << "Element Found at index : " << result.second <<std::endl;
else
	std::cout << "Element Not Found" << std::endl;

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.

// Check if any multiple of 3  exists in vector using lambda function as comparator

std::vector<int>::iterator it2 = std::find_if(vecOfNums.begin(), vecOfNums.end(), [](const int & val){
																							if (val % 3 == 0)
																								return true;
																							return false;
																						});

if (it != vecOfNums.end())
	std::cout << "Multiple of 3 Found : " << *it2 << std::endl;
else
	std::cout << "Multiple of 3 Not Found" << std::endl;

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.

bool found = false;
// Iterate over all elements in Vector
for (auto & elem : vecOfNums)
{
	if (elem == 22)
	{
		found = true;
		break;
	}
}
if(found)
	std::cout << "Element Found" << std::endl;
else
	std::cout << "Element Not Found" << std::endl;

Complete example is as follows,

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

/*
Generic function to find an element in vector and also its position.
It returns a pair of bool & int i.e.

bool : Represents if element is present in vector or not.
int : Represents the index of element in vector if its found else -1

*/
template < typename T>
std::pair<bool, int > findInVector(const std::vector<T>  & vecOfElements, const T  & element)
{
	std::pair<bool, int > result;

	// Find given element in vector
	auto it = std::find(vecOfElements.begin(), vecOfElements.end(), element);

	if (it != vecOfElements.end())
	{
		result.second = distance(vecOfElements.begin(), it);
		result.first = true;
	}
	else
	{
		result.first = false;
		result.second = -1;
	}

	return result;
}

int main()
{
	std::vector<int> vecOfNums = { 12, 45, 54, 33, 2, 7, 8, 22, 43, 19 };

	/*
	Find an element in vector using std::find
	*/

	// Check if element 22 exists in vector
	std::vector<int>::iterator it = std::find(vecOfNums.begin(), vecOfNums.end(), 22);

	if (it != vecOfNums.end())
	{
		std::cout << "Element Found" << std::endl;

		// Get index of element from iterator
		int index = std::distance(vecOfNums.begin(), it);
		std::cout <<"Index of element in vector : "<<index<<std::endl;
	}
	else
	{
		std::cout << "Element Not Found" << std::endl;
	}

	std::pair<bool, int> result = findInVector<int>(vecOfNums, 45);

	if (result.first)
		std::cout << "Element Found at index : " << result.second <<std::endl;
	else
		std::cout << "Element Not Found" << std::endl;


	/*
	 * Finding an element by custom comparator
	 */


// Check if any multiple of 3  exists in vector using lambda function as comparator

std::vector<int>::iterator it2 = std::find_if(vecOfNums.begin(), vecOfNums.end(), [](const int & val){
																							if (val % 3 == 0)
																								return true;
																							return false;
																						});

if (it != vecOfNums.end())
	std::cout << "Multiple of 3 Found : " << *it2 << std::endl;
else
	std::cout << "Multiple of 3 Not Found" << std::endl;

	/*
		Find an element in vector using c++11 range based for loop
	*/

	bool found = false;
	// Iterate over all elements in Vector
	for (auto & elem : vecOfNums)
	{
		if (elem == 22)
		{
			found = true;
			break;
		}
	}
	if(found)
		std::cout << "Element Found" << std::endl;
	else
		std::cout << "Element Not Found" << std::endl;

    return 0;
}


 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top