find index of element in array 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: how to get the index of an item in a array in c++

#include <iostream>
using namespace std;

int main() {
  int array = {1, 2, 3, 4, 5};
  for (int i = 0; i < sizeof(array)/sizeof(array[0]); i++) {
	if (array[i] == 5) {
      cout << i;
    }
  }
  return 0;
}

Tags:

Cpp Example