Пара в стандартній бібліотеці шаблонів C++ (STL)

Пара використовується для об’єднання двох значень, які можуть мати різні типи даних. Пара надає можливість зберігати два різнорідні об’єкти як єдине ціле. В основному він використовується, якщо ми хочемо зберігати кортежі. Контейнер пари — це простий контейнер, визначений у заголовок, що складається з двох елементів даних або об'єктів.

  • Перший елемент позначається як «перший», а другий елемент як «другий», і порядок є фіксованим (перший, другий).
  • Пари можна призначати, копіювати та порівнювати. Масив об’єктів, виділених у a карта або hash_map за замовчуванням має тип «пара», в якому всі «перші» елементи є унікальними ключами, пов’язаними з їхніми об’єктами «другого» значення.
  • Щоб отримати доступ до елементів, ми використовуємо ім’я змінної, за яким іде оператор крапки, а потім ключове слово first або second.

Синтаксис:

pair Pair_name 

CPP




// CPP program to illustrate Pair in STL> #include> #include> using> namespace> std;> // Driver Code> int> main()> {> > // defining a pair> > pair <> int> ,> char> >ПАРА1;> > // 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 

Ініціалізація пари: Ми також можемо ініціалізувати пару.

Синтаксис:

pair Pair_name (value1, value2) ; 

Різні способи ініціалізації пари:

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 

Іншим способом ініціалізації пари є використання функції make_pair().

g2 = make_pair(1, 'a'); 

Ще один дійсний синтаксис для оголошення пари:

g2 = {1, 'a'}; 

CPP




// CPP program to illustrate> // Initializing of pair STL> #include> #include> using> namespace> std;> // Driver Code> int> main()> {> > // defining a pair> > pairdouble>PAIR2('GeeksForGeeks', 1.23); cout < < PAIR2.first < < ' '; cout < < PAIR2.second < < endl; return 0; }>

Вихід

GeeksForGeeks 1.23 

Примітка: Якщо не ініціалізовано, перше значення пари буде ініціалізовано автоматично.

C++




// CPP program to illustrate> // auto-initializing of pair STL> #include> #include> using> namespace> std;> int> main()> {> > pair <> int> ,> double> >ПАРА1;> > pairchar>ПАРА2; // ініціалізується 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; }>

Вихід:

00 

Функції члена

1) make_pair() : ця функція шаблону дозволяє створювати пару значень без явного написання типів.
Синтаксис:

Pair_name = make_pair (value1,value2); 

CPP




// CPP Program to demonstrate make_pair()> // function in pair> #include> #include> using> namespace> std;> // Driver Code> int> main()> {> > pair <> int> ,> char> >ПАРА1;> > pairdouble>PAIR2('GeeksForGeeks', 1.23); pairdouble> PAIR3; ПАРА1.перша = 100; PAIR1.second = 'G'; PAIR3 = make_pair('GeeksForGeeks — найкращий', 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) замінити: Ця функція замінює вміст одного парного об’єкта вмістом іншого парного об’єкта. Пари мають бути одного типу.
Синтаксис:

pair1.swap(pair2) ; 

Для двох заданих пар, скажімо, pair1 і pair2 одного типу, функція swap замінить pair1.first на pair2.first і pair1.second на pair2.second.

CPP




// CPP Program to demonstrate swap()> // function in pair> #include> #include> using> namespace> std;> // Driver Code> int> main()> {> > pair <> char> ,> int> >пара1 = зробити_пару(> 'A'> , 1);> > pair <> char> ,> int> >пара2 = зробити_пару(> 'B'> , 2);> > cout < <> 'Before swapping: '> ;> > cout < <> 'Contents of pair1 = '> < < pair1.first < <> ' '> > < < pair1.second;> > cout < <> 'Contents of pair2 = '> < < pair2.first < <> ' '> > < < pair2.second;> > pair1.swap(pair2);> > cout < <> ' After swapping: '> ;> > 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) краватка(): Ця функція працює так само, як і в кортежі . Він створює кортеж із посилань lvalue на свої аргументи, тобто для розпакування значень кортежу (або тут пари) в окремі змінні. Так само, як і в кортежах, тут також є два варіанти зв'язку, з ігноруванням і без нього. Ключове слово ignore ігнорує певний елемент кортежу від розпакування.
Однак кортежі можуть мати кілька аргументів, а пари мають лише два аргументи. Таким чином, у випадку пари пар розпакування має бути оброблено явно.
Синтаксис:

tie(int &, int &) = pair1; 

CPP




// CPP code to illustrate tie() in Pair> #include> using> namespace> std;> // Driver Code> int> main()> {> > pair <> int> ,> int> >пара1 = { 1, 2 };> > int> a, b;> > tie(a, b) = pair1;> > cout < < a < <> ' '> < < b < <> ' '> ;> > pair <> int> ,> int> >пара2 = { 3, 4 };> > tie(a, ignore) = pair2;> > // prints old value of b> > cout < < a < <> ' '> < < b < <> ' '> ;> > // Illustrating pair of pairs> > pair <> int> , pair <> int> ,> char> >> пара3 = { 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> > tie(x,ignore) = pair3;> > tie(y, z) = pair3.second;> > cout < < x < <> ' '> < < y < <> ' '> < < z < <> ' '> ;> }> // contributed by sarthak_eddy.>

Вихід

1 2 3 2 3 4 a 

Код для ілюстрації функцій у парі:

CPP




// CPP program to illustrate pair in STL> #include> #include> #include> using> namespace> std;> int> main()> {> > pairint>g1; pairint> g2('Тест', 3); pairint> g3(g2); пара 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 < < ' The 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. The ' < < '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 

Часова складність: O(1).

Допоміжні приміщення: O(1).

оператори (=, ==, !=,>=, <=) у парі

Ми також можемо використовувати оператори з парами.

1) використовуючи рівний (=): Він призначає новий об’єкт для об’єкта пари. Синтаксис:

pair& operator= (const pair& pr); 

Це призначає pr як новий вміст для об’єкта пари. Першому значенню присвоюється перше значення pr, а другому значенню присвоюється друге значення pr.

2) Оператор порівняння (==) з парою: Для двох наведених пар, наприклад pair1 і pair2, оператор порівняння порівнює перше значення та друге значення цих двох пар, тобто якщо pair1.first дорівнює pair2.first чи ні, а pair1.second дорівнює pair2.second чи ні. .

тобто if ( (pari1.first ==pair2.first) && (pair1.second==pair2.second) )

Якщо будь-яка з двох умов є хибною, вона повертає false, інакше — істина.

3) Оператор нерівності (!=) з парою: Для заданих двох пар, наприклад pair1 і pair2, оператор != порівнює перші значення цих двох пар, тобто якщо pair1.first дорівнює pair2.first чи ні, якщо вони рівні, тоді він перевіряє другі значення обох.

4) Логічні (>=, <= )оператори з парою: Для заданих двох пар, скажімо, pair1 і pair2, =,> також можна використовувати з парами. Він повертає 0 або 1, порівнюючи лише перше значення пари. Для таких пар, як p1=(1,20) і p2=(1,10) p2 або

&list=PLqM7alHXFySGg6GSRmE2INI4k8fPH5qVB