A pair is exactly how it sounds, it is a pair of values. Pairs can be two values of the same type, but they can also contain values of a different type. Pairs are often used to hold two pieces of related data. You will see pairs used later as you explore key/value pairs with maps.
Creating Pairs
Pairs are part of the C++ standard library and do not need a special import statement.
To declare a pair, you use the keyword pair and specify the two types of variables inside angled brackets and then the variable name.
When creating the pair, you can assign initial values by placing them inside curly brackets.
Examples:
pair<string, int> nameAge {"Betsy", 9};
pair<double, double> math {5.3, 8.7};
Accessing and Updating Values
Accessing and updating values is similar to how values are accessed and updated with a struct. With structs, you access the value with a dot and the member name. Since a pair doesn’t have member variables, you simply access using the keywords first and second.
Example:
Output:
Updates are done using the same access.
Using Pairs
Just like any other data structure, pairs can be used as a separate data structure or as part of another data structure. In this example, you can see how pairs can be used with a vector or a queue.
Examples:
As mentioned above, pairs will be used for specific purposes in C++, like maps. Beyond that, pairs do have limited use since it can often be just as easy and more descriptive to create a struct. For example, if you wanted to store the first and last name, you can do this with a pair and then represent the first name in the first position and the last name in the second position.
Alternatively, you can create a name struct and give the member names more descriptive values such as firstName and lastName.