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
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++
#include <bits/stdc++.h>
using namespace std;
void getIndex(vector< int > v, int K)
{
auto it = find(v.begin(), v.end(), K);
if (it != v.end())
{
int index = it - v.begin();
cout << index << endl;
}
else {
cout << "-1" << endl;
}
}
int main()
{
vector< int > v = { 1, 45, 54, 71, 76, 17 };
int K = 54;
getIndex(v, K);
return 0;
}
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
10 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...