# Sets of pairs in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

Set in C++ is an associative container and contains unique elements. All the elements once added to a specific cannot be modified. One can only remove and add elements in order to change them.

Pair is defined under <utility> header and is used to couple together two pair values. The pair can have values of different or same type. The class has member functions first() and second() to individually access the values in a pair.

The order of pair elements is fixed (first, second). We can use pair to combine two heterogeneous values of different types.

To access any element we use variable_name.first for the first element and use variable_name.second for the second element of the pair.

## Set of pairs in C++

• No duplicate pair is allowed in a set of pairs.
• Elements of such a set, i.e pairs are sorted according to the key that is the first element of each pair present in the set.
• We can search for a particular pair, add pair, remove pair and can get the count of pair present.
• Syntax is −
set< pair<datatype1, datatype2> > set_name;
set < pair <int, int> > set1;

Here , set1 is an object of type set which consists of pairs of two integer types.

## Example

#include <bits/stdc++.h>
using namespace std;
int main(){
//pair<int, int> pairs;
int arr[]={ 2, 3, 1, 6, 9, 7, 10, 2 };
int n=8;
set<pair <int,int> > set1;
for (int i = 0; i < n-1 ; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] % 2 == 1 && arr[j] % 2 == 1) {
// pairs of odd numbers
pairs p1 = make_pair(arr[i], arr[j]);
// putting into the set
set1.insert(p1);
}
}
}
// to display the pairs
for (auto const &var : set1) {
cout << "(" << var.first << ", "<< var.second << ")"<< " ";
}
// to clear the set
set1.clear();
}

## Output

(1, 7) (1, 9) (3, 1) (3, 7) (3, 9) (9, 7)
Updated on 28-Jul-2020 10:50:15