how to find the index of an element in a vector c++ code example
Example 1: get index of value 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";
}
Example 2: c++ find element in vector
auto it = find(vec.begin(),vec,end(), item)!
if(it != vec.end()){
int index = it - vec.begin();
}
Example 3: c++ get vector element by index
vectorName[5];