Skip to content
Related Articles

Related Articles

How to find index of a given element in a Vector in C++
  • Difficulty Level : Easy
  • Last Updated : 29 Oct, 2020

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output: 

2



 

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

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :