A pair in C++ is a container that stores two values (like a tuple). These values may or may not be of the same data-type.
The declaration involves a keyword (pair
) followed by comma-separated data-types within < >
signs and the name of the pair.
The elements of a pair can be accessed via the first
and second
keywords.
#include <iostream>using namespace std;int main() {pair<int, string> anon_pair; // Declaring a pairanon_pair.first = 17; // Accessing the first elementanon_pair.second = "seventeen"; // Accessing the second element}
Alternatively, pairs can also be initialized in the following two ways:
#include <iostream>using namespace std;int main() {pair<int, string> pair_1(4, "four"); // 1) Declaring and initializing togetherpair<int, string> pair_2; // 2) Declaringpair_2 = make_pair(5, "five"); //Then initializing using a built-in make_pair function.}
=
) operator lets us assign the values of one pair to another.==
) operator returns true if two pairs contain the same values. The inequality (!=
) operator returns true if two pairs do not contain the same values.<
) and greater-than (>
) operators work by only comparing the first
values of the pairs being compared. The same can be said about the <=
and >=
operators.How one can use these operators is demonstrated below:
#include <iostream>using namespace std;int main() {pair<int, string> pair_1(1, "one");pair<int, string> pair_2;pair_2 = make_pair(2, "two");if (pair_1 <= pair_2) // Less-than or equal to{pair_1 = pair_2; // Assignment}if(pair_1 == pair_2) // Equality{cout<<pair_1.first<<" "<<pair_1.second<<endl;}}
Free Resources