To get the index of a specified element in an array in C++, you can use the std::find function from the
In this example,
header for using the std::find
function.arr
with values 10, 20, 30, 40, 50.std::find
function to find the iterator of element 30 in the array.std::distance
.arr.end()
.#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> arr = {10, 20, 30, 40, 50};
int specifiedElement = 30;
auto it = std::find(arr.begin(), arr.end(), specifiedElement);
if (it != arr.end()) {
int index = std::distance(arr.begin(), it);
std::cout << "Index of specified element " << specifiedElement << " is: " << index << std::endl;
} else {
std::cout << "Specified element not found in the array" << std::endl;
}
return 0;
}
Index of specified element 30 is: 2
In this example,
header for using the std::find
function.arr
with values 10, 20, 30, 40, 50.std::find
function to find the iterator of element 60 in the array.std::distance
.arr.end()
.#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> arr = {10, 20, 30, 40, 50};
int specifiedElement = 60;
auto it = std::find(arr.begin(), arr.end(), specifiedElement);
if (it != arr.end()) {
int index = std::distance(arr.begin(), it);
std::cout << "Index of specified element " << specifiedElement << " is: " << index << std::endl;
} else {
std::cout << "Specified element not found in the array" << std::endl;
}
return 0;
}
Specified element not found in the array
In this tutorial, we learned How to get the Index of Specified Element in an Array in C++ language with well detailed examples.