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

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: 2
Explaination :
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:



    • Index of an element in a vector can be found with the help of the two predefined functions in stl:

    • find(): Used to find the position of element in the vector.
    • distance(): Used to find distance between base iterater of vector and iterator return by find() function.
  1. Finaly return the distance returned by distance() function.

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 = distance(v.begin(),
                             it);
        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 DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.