Answers for "how to get the index of an element in an array in c++"

C++
4

find index of element in array c++

vector<int> arr = { 6, 3, 5, 2, 8 };
vector<int>::iterator itr = std::find(arr.begin(), arr.end(), elem);

if (itr != end(arr)) {
	cout << "Element " << elem << " is present at index " << distance(arr, itr) << " in the given array";
}
else {
	cout << "Element is not present in the given array";
}
Posted by: Guest on February-22-2020
0

c++ find index of an element

#include <iostream>
#include <vector> 
#include <iterator> 
#include <algorithm>  
using namespace std;

int main()
{
    vector<int> v = {1,2,3,4,6,4,5};
    // Get index of element from iterator
    int index = distance(v.begin(), find(v.begin(), v.end(), 4));
    cout << index;
}
Posted by: Guest on February-16-2022

Code answers related to "how to get the index of an element in an array in c++"

Browse Popular Code Answers by Language