Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2020
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. // C++ program to demonstrate sorting in vector
  2. // of pair according to 2nd element of pair
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5.  
  6. // Driver function to sort the vector elements
  7. // by second element of pairs
  8. bool sortbysec(const pair<int,int> &a,
  9. const pair<int,int> &b)
  10. {
  11. return (a.second < b.second);
  12. }
  13.  
  14. int main()
  15. {
  16. // declaring vector of pairs
  17. vector< pair <int, int> > vect;
  18.  
  19. // Initialising 1st and 2nd element of pairs
  20. // with array values
  21. int arr[] = {10, 20, 5, 40 };
  22. int arr1[] = {30, 60, 20, 50};
  23. int n = sizeof(arr)/sizeof(arr[0]);
  24.  
  25. // Entering values in vector of pairs
  26. for (int i=0; i<n; i++)
  27. vect.push_back( make_pair(arr[i],arr1[i]) );
  28.  
  29. // Printing the original vector(before sort())
  30. cout << "The vector before sort operation is:\n" ;
  31. for (int i=0; i<n; i++)
  32. {
  33. // "first" and "second" are used to access
  34. // 1st and 2nd element of pair respectively
  35. cout << vect[i].first << " "
  36. << vect[i].second << endl;
  37.  
  38. }
  39.  
  40. // Using sort() function to sort by 2nd element
  41. // of pair
  42. sort(vect.begin(), vect.end(), sortbysec);
  43.  
  44. // Printing the sorted vector(after using sort())
  45. cout << "The vector after sort operation is:\n" ;
  46. for (int i=0; i<n; i++)
  47. {
  48. // "first" and "second" are used to access
  49. // 1st and 2nd element of pair respectively
  50. cout << vect[i].first << " "
  51. << vect[i].second << endl;
  52. }
  53. return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement