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:
Minimum swaps to make two arrays consisting unique elements identical
Next article icon

Sort Vector of Pairs in Ascending Order in C++

Last Updated : 17 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Sorting a vector of pairs in ascending order means arranging the elements in such a way that first pair is lesser than second pair, second pair is lesser than third pair and so on.

The easiest way to sort the vector of pairs in ascending order is to use std::sort() function. The below code example illustrates this method:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     vector<pair<int, char>> v = {{5, 'a'},                       {1, 'c'}, {2, 'b'}};      // Sort above vector v     sort(v.begin(), v.end());      for (auto i : v)         cout << i.first << ": " << i.second       		<< endl;     return 0; } 

Output
1: c 2: b 5: a 

Explanation: By default, sort() function sorts the vector of pairs in the ascending order of the first member of pairs. If the first members are equal, then it compares the second members.

There are also other methods available in C++ to sort the vector of pairs in ascending order. Let’s look at each of them one by one.

Table of Content

  • Using sort() with Custom Comparison
  • Using stable_sort()
  • Using Multiset

Using sort() with Custom Comparison

To change the way of comparison, such as sorting on the basis of the second member of pairs, a custom comparator function that redefines the rules for comparing two pairs is used with sort().

C++
#include <bits/stdc++.h> using namespace std;  int main() {     vector<pair<int, char>> v = {{5, 'a'},                       {1, 'c'}, {2, 'b'}};      	// Comparator that compares two pairs'   	// second members   	auto comp = [](pair<int, int> a, pair                    <int,int> b) {       	return a.second < b.second;     };      // Sort the vector of pairs     sort(v.begin(), v.end(), comp);      for (auto i : v)         cout << i.first << ": " << i.second       		<< endl;     return 0; } 

Output
5: a 2: b 1: c 

Explanation: The comp lambda expression compares the second member of two pairs a and b and return true if the a.second is smaller than b.second. This function is passed to sort() as a parameter.

Using stable_sort()

The std::stable_sort() function is another sorting function available in C++ that can be used to sort the vector of pairs in ascending order just like sort() function.

C++
#include <bits/stdc++.h> using namespace std;  int main() {     vector<pair<int, char>> v = {{5, 'a'},                       {1, 'c'}, {2, 'b'}};      // Sort the vector of pairs     stable_sort(v.begin(), v.end());      for (auto i : v)         cout << i.first << ": " << i.second << endl;     return 0; } 

Output
1: c 2: b 5: a 

The stable_sort() function maintains the relative order of elements with equal keys which can be useful when you want to preserve the original order for equal elements.

Using Multiset

Elements in multiset container are stored in ascending order by default. So, we can create a std::multiset of pairs from the vector of pairs and then copy all the elements back to the vector to get it sorted.

C++
#include <bits/stdc++.h> using namespace std;  int main() {     vector<pair<int, char>> v = {{5, 'a'},                        {1, 'c'}, {2, 'b'}};      // Create the multiset with vector     multiset<pair<int, char>> ms(v.begin(),                                  v.end());          // Copy all elements of multiset   	// back to vector   	v.clear();     copy(ms.begin(), ms.end(), back_inserter(v));          for (auto i : v)         cout << i.first << ": " << i.second       		<< endl;     return 0; } 

Output
1: c 2: b 5: a 

This method is not generally used as the above methods already work for almost every scenario. It is just mentioned here for informational purpose.



Next Article
Minimum swaps to make two arrays consisting unique elements identical

M

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

Similar Reads

  • Sorting Algorithms
    A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
    3 min read
  • Introduction to Sorting Techniques – Data Structure and Algorithm Tutorials
    Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
    3 min read
  • Most Common Sorting Algorithms

    • Selection Sort
      Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element a
      8 min read
    • Bubble Sort Algorithm
      Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the fi
      8 min read
    • Insertion Sort Algorithm
      Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
      9 min read
    • Merge Sort - Data Structure and Algorithms Tutorials
      Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. How do
      14 min read
    • Quick Sort
      QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
      13 min read
    • Heap Sort - Data Structures and Algorithms Tutorials
      Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
      14 min read
    • Counting Sort - Data Structures and Algorithms Tutorials
      Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
      9 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