Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
Program to sort string in descending order
Next article icon

Sort Vector of Pairs in descending order in C++

Last Updated : 06 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

We have discussed some of the cases of sorting vector of pairs in below set 1.

Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)

More cases are discussed in this article. Sometimes we require to sort the vector in reverse order. In those instances, rather than first sorting the vector and later using “reverse” function increases the time complexity of the code. Therefore, to avoid this we sort the vector in descending order directly.

Case 3 : Sorting the vector elements on the basis of first element of pairs in descending order.

This type of sorting arranges selected rows of pairs in vector in descending order. This is achieved by using “sort()” and passing iterators of 1D vector as its arguments.

C++




// C++ program to demonstrate sorting in vector of
// pair according to 1st element of pair in
// descending order
 
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    // declaring vector of pairs
    vector<pair<int, int> > vect;
 
    // initializing 1st and 2nd element of
    // pairs with array values
    int arr[] = { 5, 20, 10, 40 };
    int arr1[] = { 30, 60, 20, 50 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Entering values in vector of pairs
    for (int i = 0; i < n; i++)
        vect.push_back(make_pair(arr[i], arr1[i]));
 
    // Printing the original vector(before sort())
    cout << "The vector before applying sort is:\n";
    for (int i = 0; i < n; i++) {
        // "first" and "second" are used to access
        // 1st and 2nd element of pair respectively
        cout << vect[i].first << " " << vect[i].second
             << endl;
    }
 
    // using modified sort() function to sort
    sort(vect.rbegin(), vect.rend());
 
    // Printing the sorted vector(after using sort())
    cout << "The vector after applying sort is:\n";
    for (int i = 0; i < n; i++) {
        // "first" and "second" are used to access
        // 1st and 2nd element of pair respectively
        cout << vect[i].first << " " << vect[i].second
             << endl;
    }
    return 0;
}
 
 

C++




// C++ program to demonstrate sorting in vector of
// pair according to 1st element of pair in
// descending order using STL sort function
 
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    // declaring vector of pairs
    vector<pair<int, int> > vect;
 
    // initializing 1st and 2nd element of
    // pairs with array values
    int arr[] = { 5, 20, 10, 40 };
    int arr1[] = { 30, 60, 20, 50 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Entering values in vector of pairs
    for (int i = 0; i < n; i++)
        vect.push_back({arr[i], arr1[i]});
 
    // Printing the original vector(before sort())
    cout << "The vector before applying sort is:\n";
    for (int i = 0; i < n; i++) {
        // "first" and "second" are used to access
        // 1st and 2nd element of pair respectively
        cout << vect[i].first << " " << vect[i].second
             << endl;
    }
 
    // modifying sort function by adding 3rd parameter
      // to sort the vector of pair in descending order
    sort(vect.begin(), vect.end(),
         greater<pair<int, int> >());
 
    // Printing the sorted vector(after using sort())
    cout << "The vector after applying sort is:\n";
    for (int i = 0; i < n; i++) {
        // "first" and "second" are used to access
        // 1st and 2nd element of pair respectively
        cout << vect[i].first << " " << vect[i].second
             << endl;
    }
    return 0;
}
 
 
Output
The vector before applying sort is: 5 30 20 60 10 20 40 50 The vector after applying sort is: 40 50 20 60 10 20 5 30

Time Complexity: O(N*logN), where N is the size of the vector.
Auxiliary Space: O(N) 

Case 4 : Sorting the vector elements on the basis of second element of pairs in descending order.

These instances can also be handled by modifying “sort()” function and again passing a call to user-defined function.

CPP




// C++ program to demonstrate sorting/in vector of
// pair according to 2nd element of pair in
// descending order
#include<bits/stdc++.h>
using namespace std;
 
// Driver function to sort the vector elements by
// second element of pair in descending order
bool sortbysecdesc(const pair<int,int> &a,
                   const pair<int,int> &b)
{
       return a.second>b.second;
}
 
 
int main()
{
    // Declaring vector of pairs
    vector< pair <int,int> > vect;
 
    // Initializing 1st and 2nd element of
    // pairs with array values
    int arr[] = {5, 20, 10, 40 };
    int arr1[] = {30, 60, 20, 50};
    int n = sizeof(arr)/sizeof(arr[0]);
 
    // Entering values in vector of pairs
    for (int i=0; i<n; i++)
        vect.push_back( make_pair(arr[i],arr1[i]) );
 
    // Printing the original vector(before sort())
    cout << "The vector before sort operation is:\n" ;
    for (int i=0; i<n; i++)
    {
        // "first" and "second" are used to access
        // 1st and 2nd element of pair respectively
        cout << vect[i].first << " "
            << vect[i].second << endl;
    }
 
    // using modified sort() function to sort
    sort(vect.begin(), vect.end(), sortbysecdesc);
 
    // Printing the sorted vector(after using sort())
    cout << "The vector after applying sort operation is:\n" ;
    for (int i=0; i<n; i++)
    {
        // "first" and "second" are used to access
        // 1st and 2nd element of pair respectively
        cout << vect[i].first << " "
             << vect[i].second << endl;
    }
    return 0;
}
 
 
Output
The vector before sort operation is: 5 30 20 60 10 20 40 50 The vector after applying sort operation is: 20 60 40 50 5 30 10 20

Time Complexity: O(N*logN), where N is the size of the vector.
Auxiliary Space: O(N) 

 



Next Article
Program to sort string in descending order

M

Manjeet Singh
Improve
Article Tags :
  • C Language
  • C++
  • DSA
  • Sorting
  • CPP-Library
  • STL
Practice Tags :
  • CPP
  • Sorting
  • STL

Similar Reads

  • How to Sort a Vector in Descending Order Using STL in C++?
    Sorting vector in descending order means arranging the elements in such a way that the first element will be largest, and second element will be second largest and so on. In C++, the simplest way to sort the vector in descending order is to by using the sort() function with a custom comparator. [GFG
    3 min read
  • Sort vector of Numeric Strings in ascending order
    Given a vector of numeric strings arr[], the task is to sort the given vector of numeric strings in ascending order. Examples: Input: arr[] = {"120000", "2", "33"}Output: {"2", "33", "120000"} Input: arr[] = {"120", "2", "3"}Output: {"2", "3", "120"} Approach: The sort() function in C++ STL is able
    5 min read
  • Sorting of Vector of Tuple in C++ (Ascending Order)
    What is the Vector of a Tuple?A tuple is an object that can hold several elements and a vector containing multiple numbers of such a tuple is called a vector of the tuple. The elements can be of different data types. The elements of tuples are initialized as arguments in the order in which they will
    4 min read
  • Sorting 2D Vector in C++ | Set 2 (In descending order by row and column)
    We have discussed some of the cases of sorting 2D vector in below set 1. Sorting 2D Vector in C++ | Set 1 (By row and column) More cases are discussed in this article Case 3 : To sort a particular row of 2D vector in descending order This type of sorting arranges a selected row of 2D vector in desce
    4 min read
  • Program to sort string in descending order
    Given a string, sort it in descending order. Examples: Input : alkasingh Output : snlkihgaa Input : nupursingh Output : uusrpnnihg Input : geeksforgeeks Output : ssrokkggfeeee Recommended PracticeSort the string in descending orderTry It! A simple solution is to use library sort function std::sort()
    7 min read
  • Sorting 2D Vector of Pairs in C++
    A 2D vector also known as vector of vectors is a vector in which each element is a vector on its own. In other words, It is a matrix implemented with the help of vectors. What is a 2D vector of pairs? A 2D vector of pairs is a vector in which each element is a vector of pairs on its own. In other wo
    15+ min read
  • Sort a string in increasing order of given priorities
    Given an alphanumeric string S of length N, the task is to sort the string in increasing order of their priority based on the following conditions: Characters with even ASCII values have higher priority than characters with odd ASCII values.Even digits have higher priority than odd digits.Digits hav
    8 min read
  • Stable sort for descending order
    Given an array of n integers, we have to reverse sort the array elements such the equal keys are stable after sorting. Examples: Input : arr[] = {4, 2, 3, 2, 4} Output : 4, 4, 3, 2, 2 Prerequisite : Stability in sorting algorithmsMethod 1 (Writing our own sorting function : Bubble Sort)We know sorti
    8 min read
  • Descending Order in Map and Multimap of C++ STL
    We have discussed map in C++ STL and multimap in C++ STL. The default behavior of these data structures is to store elements in ascending order. How to store elements in reverse order or descending order when inserting in map and multimap? We can use the third parameter, that is std::greater along w
    3 min read
  • Sort an array of Roman Numerals in ascending order
    Given an array arr[] of N Roman Numerals, the task is to sort these Roman Numerals in ascending order. Examples: Input: arr[] = { "MCMIV", "MIV", "MCM", "MMIV" } Output: MIV MCM MCMIV MMIV Explanation: The roman numerals in their corresponding decimal system are: MIV: 1004 MCM: 1900 MCMIV: 1904 MMIV
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences