Find index of first occurrence when an unsorted array is sorted | C ++ program to find index of first occurrence of x when array is sorted . ; lower_bound returns iterator pointing to first element that does not compare less to x . ; If x is not present return - 1. ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findFirst ( int arr [ ] , int n , int x ) { sort ( arr , arr + n ) ; int * ptr = lower_bound ( arr , arr + n , x ) ; return ( * ptr != x ) ? -1 : ( ptr - arr ) ; } int main ( ) { int x = 20 , arr [ ] = { 10 , 30 , 20 , 50 , 20 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findFirst ( arr , n , x ) ; return 0 ; }