Open In App

How to find index of a given element in a Vector in C++

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given a vector V consisting of N integers and an element K, the task is to find the index of element K in the vector V. If the element does not exist in vector then print -1.

Examples: 

Input: V = {1, 45, 54, 71, 76, 17}, K = 54 
Output:
Explanation : 
The index of 54 is 2, hence output is 2.
Input: V = {3, 7, 9, 11, 13}, K = 12 
Output: -1 

Approach: 
Follow the steps below to solve the problem:  

  • find(): Used to find the position of element in the vector.
  • Subtract from the iterator returned from the find function, the base iterator of the vector .
  • Finally return the index returned by the subtraction.

Below is the implementation of the above approach :  

C++




// C++ program to find the index
// of an element in a vector
#include <bits/stdc++.h>
using namespace std;
  
// Function to print the
// index of an element
void getIndex(vector<int> v, int K)
{
    auto it = find(v.begin(), v.end(), K);
  
    // If element was found
    if (it != v.end()) 
    {
      
        // calculating the index
        // of K
        int index = it - v.begin();
        cout << index << endl;
    }
    else {
        // If the element is not
        // present in the vector
        cout << "-1" << endl;
    }
}
// Driver Code
int main()
{
    // Vector
    vector<int> v = { 1, 45, 54, 71, 76, 17 };
    // Value whose index
    // needs to be found
    int K = 54;
    getIndex(v, K);
    return 0;
}


Output: 

2



 

Time Complexity: O(N) 
Auxiliary Space: O(1)


Last Updated : 10 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads