Un par es un contenedor que almacena dos valores asignados entre sí, y un vector que contiene múltiples números de dichos pares se denomina vector de pares .
Al resolver problemas, surgen muchos casos en los que es necesario clasificar los elementos del vector en función del primer y segundo elemento del par. En ese caso, tenemos que pasar un argumento adicional a la función sort() i, una llamada a una función explícita definida por el usuario en la función sort().
Este artículo se enfoca en discutir el vector de clasificación de pares sobre la base del primer elemento de pares en orden ascendente y si el primer elemento es igual, entonces según el segundo elemento en orden descendente.
A continuación se muestra el programa C++ para demostrar la clasificación de vectores de pares.
C++
// C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to sort the vector elements // ascending for first element // and if first element equal // then descending for second element bool sortbyCond(const pair<int, int>& a, const pair<int, int>& b) { if (a.first != b.first) return (a.first < b.first); else return (a.second > b.second); } // Driver code int main() { // Declaring vector of pairs vector<pair<int, int> > vect; // Initialising 1st and 2nd element // of pairs with array values int arr[] = { 10, 10, 5, 5, 15, 15 }; int arr1[] = { 40, 60, 20, 50, 12, 24 }; 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])); // 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 sort() function to sort by // 1st element of pair and if first // element equal then by descending // order of second element sort(vect.begin(), vect.end(), sortbyCond); // Printing the sorted vector(after // using sort()) cout << "The vector after 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; }
Java
// Java program to implement // the above approach import java.util.*; class GFG{ static class pair implements Comparable<pair> { int first,second; pair(int s, int e) { first = s; second = e; } // Function to sort the vector elements // ascending for first element // and if first element equal // then descending for second element public int compareTo(pair b) { if (this.first != b.first) return (this.first < b.first)?-1:1; else return this.second > b.second?-1:1; } } // Driver code public static void main(String[] args) { // Declaring vector of pairs List<pair > vect = new ArrayList<pair > (); // Initialising 1st and 2nd element // of pairs with array values int arr[] = { 10, 10, 5, 5, 15, 15 }; int arr1[] = { 40, 60, 20, 50, 12, 24 }; int n = arr.length; // Entering values in vector of pairs for (int i = 0; i < n; i++) vect.add(new pair(arr[i], arr1[i])); // The original vector(before sort()) System.out.print("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 System.out.print(vect.get(i).first+ " " + vect.get(i).second +"\n"); } // Using sort() function to sort by // 1st element of pair and if first // element equal then by descending // order of second element Collections.sort(vect); // Printing the sorted vector(after // using sort()) System.out.print("The vector after 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 System.out.print(vect.get(i).first+ " " + vect.get(i).second +"\n"); } } } // This code is contributed by 29AjayKumar
Python3
# Python program to implement # the above approach # Function to sort the vector elements # ascending for first element # and if first element equal # then descending for second element from functools import cmp_to_key def sortbyCond(a, b): if (a[0] != b[0]): return (a[0] - b[0]) else: return b[1] - a[1] # Driver code # Declaring vector of pairs vect = [] # Initialising 1st and 2nd element # of pairs with array values arr = [ 10, 10, 5, 5, 15, 15 ] arr1 = [ 40, 60, 20, 50, 12, 24 ] n = len(arr) # Entering values in vector of pairs for i in range(n): vect.append([arr[i],arr1[i]]) # The original vector(before sort()) print("The vector before sort operation is: ") for i in range(n): # "first" and "second" are used to # access 1st and 2nd element of pair # respectively print(f"{vect[i][0]} {vect[i][1]}") # Using sort() function to sort by # 1st element of pair and if first # element equal then by descending # order of second element vect.sort(key = cmp_to_key(sortbyCond)) # Printing the sorted vector(after # using sort()) print("The vector after sort operation is: ") for i in range(n): # "first" and "second" are used to # access 1st and 2nd element of pair # respectively print(f"{vect[i][0]} {vect[i][1]}") # This code is contributed by shinjanpatra
C#
// C# program to implement // the above approach using System; using System.Collections.Generic; public class GFG{ class pair : IComparable<pair> { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } public int CompareTo(pair b) { if (this.first != b.first) return (this.first < b.first)?-1:1; else return this.second > b.second?-1:1; } } // Driver code public static void Main(String[] args) { // Declaring vector of pairs List<pair > vect = new List<pair > (); // Initialising 1st and 2nd element // of pairs with array values int []arr = { 10, 10, 5, 5, 15, 15 }; int []arr1 = { 40, 60, 20, 50, 12, 24 }; int n = arr.Length; // Entering values in vector of pairs for (int i = 0; i < n; i++) vect.Add(new pair(arr[i], arr1[i])); // The original vector(before sort()) Console.Write("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 Console.Write(vect[i].first+ " " + vect[i].second +"\n"); } // Using sort() function to sort by // 1st element of pair and if first // element equal then by descending // order of second element vect.Sort(); // Printing the sorted vector(after // using sort()) Console.Write("The vector after 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 Console.Write(vect[i].first+ " " + vect[i].second +"\n"); } } } // This code is contributed by shikhasingrajput
Javascript
<script> // JavaScript program to implement // the above approach // Function to sort the vector elements // ascending for first element // and if first element equal // then descending for second element function sortbyCond(a,b) { if (a[0] != b[0]) return (a[0] - b[0]); else return b[1] - a[1]; } // Driver code // Declaring vector of pairs let vect = []; // Initialising 1st and 2nd element // of pairs with array values let arr = [ 10, 10, 5, 5, 15, 15 ] let arr1 = [ 40, 60, 20, 50, 12, 24 ] let n = arr.length // Entering values in vector of pairs for (let i = 0; i < n; i++) vect.push([arr[i],arr1[i]]); // The original vector(before sort()) document.write("The vector before sort operation is: "); for (let i = 0; i < n; i++) { // "first" and "second" are used to // access 1st and 2nd element of pair // respectively document.write(vect[i][0] + " " + vect[i][1]); } // Using sort() function to sort by // 1st element of pair and if first // element equal then by descending // order of second element vect.sort(sortbyCond); // Printing the sorted vector(after // using sort()) document.write("The vector after sort operation is: "); for (let i = 0; i < n; i++) { // "first" and "second" are used to // access 1st and 2nd element of pair // respectively document.write(vect[i][0] + " " +vect[i][1]); } // This code is contributed by shinjanpatra </script>
The vector before sort operation is: 10 40 10 60 5 20 5 50 15 12 15 24 The vector after sort operation is: 5 50 5 20 10 60 10 40 15 24 15 12
Publicación traducida automáticamente
Artículo escrito por nishithjbaravkar y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA