Find index of an element in a C++ array
This post will discuss how to find the index of the first occurrence of an element in a C++ array.
1. Using std::find
The C++ standard library offers the std::find function which returns an iterator to the first matching element in the specified range, or an iterator to the end of the sequence if the element is not found. It can be used as follows to find the index of a value in an array in C++:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <algorithm> int main() { int arr[] = {1, 3, 5, 7, 9}; int target = 7; auto it = std::find(std::begin(arr), std::end(arr), target); if (it != std::end(arr)) { int index = std::distance(arr, it); std::cout << "Element found at index " << index << std::endl; } else { std::cout << "Element not found" << std::endl; } return 0; } |
Output:
Element found at index 3
The above solution uses std::distance to find the distance between iterators. We can also apply the pointer arithmetic to get the required index.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <algorithm> int main() { int arr[] = {1, 3, 5, 7, 9}; int target = 7; auto it = std::find(std::begin(arr), std::end(arr), target); if (it != std::end(arr)) { int index = it - std::begin(arr); std::cout << "Element found at index " << index << std::endl; } else { std::cout << "Element not found" << std::endl; } return 0; } |
Output:
Element found at index 3
2. Using Custom Routine
We can also implement our custom function to return the index of the first occurrence of the specified element in an array. The idea is to perform a linear search on the array using a regular for loop, and terminate the search on the first matching item. If the array is sorted, we can use the binary search algorithm.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <iostream> #include <algorithm> int findIndex(int arr[], int n, int target) { for (int i = 0; i < n; i++) { if (arr[i] == target) { return i; } } return -1; } int main() { int arr[] = {1, 3, 5, 7, 9}; int target = 7; int n = sizeof(arr) / sizeof(*arr); int index = findIndex(arr, n, target); if (index != -1) { std::cout << "Element found at index " << index << std::endl; } else { std::cout << "Element not found" << std::endl; } return 0; } |
Output:
Element found at index 3
That’s all about finding the index of the first occurrence of an element in a C++ array.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)