Closest greater element for every array element from another array | CPP to find result from target array for closest element ; Function for printing resultant array ; change arr [ ] to vector ; sort vector for ease ; iterator for upper_bound ; vector for result ; calculate resultant array ; check upper bound element ; if no element found push - 1 ; Else push the element ; add to resultant ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void closestResult ( int a [ ] , int b [ ] , int n ) { vector < int > vect ( a , a + n ) ; sort ( vect . begin ( ) , vect . end ( ) ) ; vector < int > :: iterator up ; vector < int > c ; for ( int i = 0 ; i < n ; i ++ ) { up = upper_bound ( vect . begin ( ) , vect . end ( ) , b [ i ] ) ; if ( up == vect . end ( ) ) c . push_back ( -1 ) ; else c . push_back ( * up ) ; } cout << " Result ▁ = ▁ " ; for ( auto it = c . begin ( ) ; it != c . end ( ) ; it ++ ) cout << * it << " ▁ " ; } int main ( ) { int a [ ] = { 2 , 5 , 6 , 1 , 8 , 9 } ; int b [ ] = { 2 , 1 , 0 , 5 , 4 , 9 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; closestResult ( a , b , n ) ; return 0 ; }