Un par se usa para combinar dos valores que pueden ser de diferentes tipos de datos. Un par proporciona una forma de almacenar dos objetos heterogéneos como una sola unidad. Básicamente se utiliza si queremos almacenar tuplas. El contenedor par es un contenedor simple definido en i
- El primer elemento se denomina ‘primero’ y el segundo elemento como ‘segundo’ y el orden es fijo (primero, segundo).
- Un par se puede asignar, copiar y comparar. La matriz de objetos asignados a un mapa o hash_map es por defecto del tipo ‘par’ y todos los elementos ‘primeros’ son claves únicas asociadas con sus objetos de valor ‘segundo’.
- Para acceder a los elementos, usamos un nombre de variable y un operador de punto con la palabra clave primero o segundo.
Sintaxis:
pair (data_type1, data_type2) Pair_name
CPP
// CPP program to illustrate Pair in STL #include <iostream> #include <utility> using namespace std; // Driver Code int main() { // defining a pair pair< int , char > PAIR1; // first part of the pair PAIR1.first = 100; // second part of the pair PAIR1.second = 'G' ; cout << PAIR1.first << " " ; cout << PAIR1.second << endl; return 0; } |
100 G
Comenzando un par: También podemos inicializar un par.
Sintaxis:
pair (data_type1, data_type2) Pair_name (value1, value2) ;
Diferentes formas de inicializar un par:
pair g1; //default pair g2(1, 'a'); //initialized, different data type pair g3(1, 10); //initialized, same data type pair g4(g3); //copy of g3
Otra forma de iniciar un par es usar la función make_pair().
g2 = make_pair(1, 'a');
Otra sintaxis válida para declarar un par es:
g2 = {1, 'a'};
CPP
// CPP program to illustrate // Initializing of pair STL #include <iostream> #include <utility> using namespace std; // Driver Code int main() { // defining a pair pair<string, double > PAIR2( "GeeksForGeeks" , 1.23); cout << PAIR2.first << " " ; cout << PAIR2.second << endl; return 0; } |
GeeksForGeeks 1.23
Nota: Si no se inicializa, el primer valor del par se inicializará automáticamente.
C++
// CPP program to illustrate // auto-initializing of pair STL #include <iostream> #include <utility> using namespace std; int main() { pair< int , double > PAIR1; pair<string, char > PAIR2; // it is initialised to 0 cout << PAIR1.first; // it is initialised to 0 cout << PAIR1.second; cout << " " ; // // it prints nothing i.e NULL cout << PAIR2.first; // it prints nothing i.e NULL cout << PAIR2.second; return 0; } |
Producción:
00
Funciones de miembros
1) hacer_par(): Esta función de plantilla permite crear un par de valores sin escribir explícitamente los tipos.
Sintaxis:
Pair_name = make_pair (value1,value2);
CPP
// CPP Program to demonstrate make_pair() // function in pair #include <iostream> #include <utility> using namespace std; // Driver Code int main() { pair< int , char > PAIR1; pair<string, double > PAIR2( "GeeksForGeeks" , 1.23); pair<string, double > PAIR3; PAIR1.first = 100; PAIR1.second = 'G' ; PAIR3 = make_pair( "GeeksForGeeks is Best" , 4.56); cout << PAIR1.first << " " ; cout << PAIR1.second << endl; cout << PAIR2.first << " " ; cout << PAIR2.second << endl; cout << PAIR3.first << " " ; cout << PAIR3.second << endl; return 0; } |
100 G GeeksForGeeks 1.23 GeeksForGeeks is Best 4.56
2) intercambio: Esta función intercambia el contenido de un par de objetos con el contenido de otro par de objetos. Los pares deben ser del mismo tipo.
Sintaxis:
pair1.swap(pair2) ;
Para dos pares dados, digamos par1 y par2 del mismo tipo, la función de intercambio intercambiará el par1.primero con el par2.primero y el par1.segundo con el par2.segundo.
CPP
// CPP Program to demonstrate swap() // function in pair #include <iostream> #include <utility> using namespace std; // Driver Code int main() { pair< char , int > pair1 = make_pair( 'A' , 1); pair< char , int > pair2 = make_pair( 'B' , 2); cout << "Before swapping:n " ; cout << "Contents of pair1 = " << pair1.first << " " << pair1.second; cout << "Contents of pair2 = " << pair2.first << " " << pair2.second; pair1.swap(pair2); cout << "nAfter swapping:n " ; cout << "Contents of pair1 = " << pair1.first << " " << pair1.second; cout << "Contents of pair2 = " << pair2.first << " " << pair2.second; return 0; } |
Before swapping: Contents of pair1 = A 1Contents of pair2 = B 2 After swapping: Contents of pair1 = B 2Contents of pair2 = A 1
3) empate(): Esta función funciona igual con las tuplas. Crea una tupla de referencias de lvalue para sus argumentos, es decir, desempaqueta los valores de la tupla (o aquí el par) en variables separadas. Al igual que las tuplas, aquí también hay dos versiones de enlace, con «ignorar» y sin «ignorar». La palabra clave «ignorar» ignora el desempaquetado de un elemento de tupla en particular.
Sin embargo, las tuplas pueden tener múltiples argumentos, mientras que los pares solo tienen dos argumentos. Por lo tanto, en el caso de un par, el desembalaje debe gestionarse de forma explícita.
Sintaxis:
tie(int &, int &) = pair1;
CPP
// CPP code to illustrate tie() in Pair #include <bits/stdc++.h> using namespace std; // Driver Code int main() { pair< int , int > pair1 = { 1, 2 }; int a, b; tie(a, b) = pair1; cout << a << " " << b << "n" ; pair< int , int > pair2 = { 3, 4 }; tie(a, ignore) = pair2; // prints old value of b cout << a << " " << b << "n" ; // Illustrating pair of pairs pair< int , pair< int , char > > pair3 = { 3, { 4, 'a' } }; int x, y; char z; // tie(x,y,z) = pair3; Gives compilation error // tie(x, tie(y,z)) = pair3; Gives compilation error // Each pair needs to be explicitly handled x = pair3.first; tie(y, z) = pair3.second; cout << x << " " << y << " " << z << "n" ; } // contributed by sarthak_eddy. |
1 2 3 2 3 4 a
Código para representar funciones emparejadas:
CPP
// CPP program to illustrate pair in STL #include <iostream> #include <string> #include <utility> using namespace std; int main() { pair<string, int > g1; pair<string, int > g2( "Quiz" , 3); pair<string, int > g3(g2); pair< int , int > g4(5, 10); g1 = make_pair(string( "Geeks" ), 1); g2.first = ".com" ; g2.second = 2; cout << "This is pair g" << g1.second << " with " << "value " << g1.first << "." << endl << endl; cout << "This is pair g" << g3.second << " with value " << g3.first << "This pair was initialized as a copy of " << "pair g2" << endl << endl; cout << "This is pair g" << g2.second << " with value " << g2.first << "nThe values of this pair were" << " changed after initialization." << endl << endl; cout << "This is pair g4 with values " << g4.first << " and " << g4.second << " made for showing addition. nThe " << "sum of the values in this pair is " << g4.first + g4.second << "." << endl << endl; cout << "We can concatenate the values of" << " the pairs g1, g2 and g3 : " << g1.first + g3.first + g2.first << endl << endl; cout << "We can also swap pairs " << "(but type of pairs should be same) : " << endl; cout << "Before swapping, " << "g1 has " << g1.first << " and g2 has " << g2.first << endl; swap(g1, g2); cout << "After swapping, " << "g1 has " << g1.first << " and g2 has " << g2.first; return 0; } |
This is pair g1 with value Geeks. This is pair g3 with value QuizThis pair was initialized as a copy of pair g2 This is pair g2 with value .com The values of this pair were changed after initialization. This is pair g4 with values 5 and 10 made for showing addition. The sum of the values in this pair is 15. We can concatenate the values of the pairs g1, g2 and g3 : GeeksQuiz.com We can also swap pairs (but type of pairs should be same) : Before swapping, g1 has Geeks and g2 has .com After swapping, g1 has .com and g2 has Geeks
operadores (=, ==, !=, >=, <=) en par
También podemos usar operadores con pares.
1) usando igual(=): Asigna un nuevo objeto a un par de objetos. Sintaxis:
pair& operator= (const pair& pr);
Esto asigna «pr» como un nuevo objeto al objeto «par». El primer valor se asigna al primer valor pr y el segundo valor se asigna al segundo valor pr.
2) Operador de comparación (==) con un par: Para los dos pares dados, digamos par1 y par2, el operador de comparación compara “el primer valor y el segundo valor de esos dos pares, es decir. es par1.primero igual a par2.primero o no” y “si par1.segundo es igual a par2. segundo o no”.
es decir, si ((par1.primero ==par2.primero) && (par1.segundo==par2.segundo) )
Si alguna de las dos condiciones es falsa, devuelve falso, de lo contrario, es verdadero.
3) Operador no igual (!=) a un par: Para los dos pares dados, digamos par1 y par2, el operador != compara los primeros valores de esos dos pares, es decir. si par1.primero es igual a par2.primero o no, si son iguales, comprueba el segundo valor de los dos pares.
4) Operadores lógicos ( >=, <= ) con un par: Para los dos pares dados digamos par1 y par2, el =, >, también se puede usar con pares. Devuelve 0 o 1 comparando solo el primer valor del par. Para pares como p1=(1,20) y p2=(1,10) p2 debería dar
&list=PLqM7alHXFySGg6GSRME2INI4k8fPH5qVB
Este artículo ha sido agregado MAZHAR IMAM KHAN. Si te gusta GeeksforGeeks y quieres contribuir, también puedes escribir un artículo usándolo. escribir.geeksforgeeks.org o envíe su artículo por correo a review-team@geeksforgeeks.org. Vea su artículo destacado en la página principal de GeeksforGeeks y ayude a otros Geeks. Escriba un comentario si encuentra algún problema o si desea compartir más información sobre el tema tratado anteriormente.