Print elements of an array according to the order defined by another array | set 2 | A C ++ program to print an array according to the order defined by another array ; Function to print an array according to the order defined by another array ; Declaring map and iterator ; Store the frequency of each number of a1 [ ] int the map ; Traverse through a2 [ ] ; Check whether number is present in map or not ; Print that number that many times of its frequency ; Print those numbers that are not present in a2 [ ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void print_in_order ( int a1 [ ] , int a2 [ ] , int n , int m ) { map < int , int > mp ; map < int , int > :: iterator itr ; for ( int i = 0 ; i < n ; i ++ ) mp [ a1 [ i ] ] ++ ; for ( int i = 0 ; i < m ; i ++ ) { if ( mp . find ( a2 [ i ] ) != mp . end ( ) ) { itr = mp . find ( a2 [ i ] ) ; for ( int j = 0 ; j < itr -> second ; j ++ ) cout << itr -> first << " ▁ " ; mp . erase ( a2 [ i ] ) ; } } for ( itr = mp . begin ( ) ; itr != mp . end ( ) ; itr ++ ) { for ( int j = 0 ; j < itr -> second ; j ++ ) cout << itr -> first << " ▁ " ; } cout << endl ; } int main ( ) { int a1 [ ] = { 2 , 1 , 2 , 5 , 7 , 1 , 9 , 3 , 6 , 8 , 8 } ; int a2 [ ] = { 2 , 1 , 8 , 3 } ; int n = sizeof ( a1 ) / sizeof ( a1 [ 0 ] ) ; int m = sizeof ( a2 ) / sizeof ( a2 [ 0 ] ) ; print_in_order ( a1 , a2 , n , m ) ; return 0 ; }