How to Find the Index of an Element in an Array in C++?
Given an array of n elements, the task is to find the index of a specific element in C++.
Examples
Input: arr[] = {11, 13, 9, 21, 51, 1000}, val = 9
Output: 2
Explanation: As the value 9 is present at index 2.Input: arr[] = {5, 8, 12, 9, 11, 32}, val = 11
Output: 4
Explanation: As the value 11 is present at index 4.
Following are the 2 different ways to find the index of a specific element in the given array in C++:
Table of Content
Using std::find()
To find the index of an element in an array in C++, we can use the std::find() function that searches the element in the given range and returns the pointer to the matching element. We can then find the index by subtracting the pointer to the beginning of the array from this pointer.
Syntax of std::find()
find(arr, arr + n, val);
where n is the size of array arr.
Example
// C++ Program to find the index of an
// element in an array using std::find()
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {11, 13, 9, 21, 51, 1000};
int n = sizeof(arr) / sizeof(arr[0]);
int val = 9;
// Using find() to get the pointer to the
// first occurence of value
auto ptr = find(arr, arr + n, val);
// Getting index from pointer
int idx = ptr - arr;
// Checking if the element found or not
if (idx >= n)
cout << "Element not Found!";
else
cout << idx;
return 0;
}
Output
2
Time Complexity: O(n), where n is the size of the array.
Auxiliary Space: O(1)
Manually Using Linear Search
We can also find the index of an element in array manually using linear search algorithm which is nothing but running the loop in the given range and checking if any element is equal to the searched element using if statement.
Example
// C++ Program for finding the index of an
// element in an array using linear search
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {11, 13, 9, 21, 51, 1000};
int n = sizeof(arr) / sizeof(arr[0]);
int val = 9;
// Index variable
int idx;
// Searching for value in the array using loop
for (idx = 0; idx < n; idx++) {
if (arr[idx] == val) {
break;
}
}
// Checking if the element found or not
if (idx == -1)
cout << "Element not Found!\n";
else
cout << idx;
return 0;
}
Output
2
Time Complexity: O(n), where n is the size of the array.
Auxiliary Space: O(1)