Find index/position of element in vector in C++

In this tutorial, we are going to learn how to find the index or position of an element in the vector with its implementation in C++.

Vectors are like dynamic arrays. They can grow or shrink automatically as needed when an element is inserted or deleted.

C++ code to find the Index of an element in the vector

First, let us create a vector and insert values into it.

#include <iostream>
#include <vector> // For handling vectors
using namespace std;

int main ()
{
  // Declaring a vector of type int
  vector <int> v;
  // inserting values into the vector
  v.push_back (1); 
  v.push_back (8); 
  v.push_back (91); 
  v.push_back (63);
  v.push_back (11); 
  v.push_back (18); 
  v.push_back (75); 

Let us now fetch the element from the user for which we need to find the position.

int i;
cout << "Enter the element ";
cin >> i;

Create an iterator to point to the elements of the vector.

vector <int> :: iterator itr;

Initialize the iterator to find method. The find method tries to find the element in the given range of elements. The find method is present in the algorithm header. So, include it at the beginning of the code.

#include <algorithm>
itr = find (v.begin(), v.end(), i);

If it is found, then it returns an iterator to the element in the range. Else if no such element is found, then the iterator reaches the end of the range.

  if (itr != v.end ())
  {
    int index = distance (v.begin (), itr);
    cout << "Element found at index/position : " << index;
  }
  else
  {
    cout << "Element not found";
  }
  return 0;
}

The vector we created is:

vector

Here, the index of the element 63 is 3.

Output:

Enter the element

63

Element found at index/position : 3

 

You may also read,

Leave a Reply

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