pair
It is a template class in the C++ standard library, used to store a combination of two objects. It is located <utility>
in the header file.
pair
The class is defined as follows:
template <class T1, class T2>
struct pair {
T1 first;
T2 second;
pair();
pair(const T1& x, const T2& y);
template<class U, class V>
pair(U&& x, V&& y);
template<class U, class V>
pair(const pair<U, V>& p);
template<class U, class V>
pair(pair<U, V>&& p) noexcept;
pair(const pair& p) = default;
pair(pair&& p) noexcept = default;
}
pair
The class has two public member variables: first
and second
, which are used to store two objects respectively. The type of member variables can be any type, including built-in types, custom types, pointer types, etc.
Here is a pair
sample code using the class:
#include <iostream>
#include <utility>
int main() {
std::pair<std::string, int> myPair("apple", 3);
std::cout << "Fruit: " << myPair.first << std::endl;
std::cout << "Count: " << myPair.second << std::endl;
return 0;
}
In the above example, we created an pair
object myPair
where first
the member is a string "apple" and second
the member is an integer 3. We then use .
the operator to access and output myPair
the object's first
and second
members.
Example output:
Fruit: apple
Count: 3
To summarize, pair
a class is a convenient tool for combining two objects together and can be used in a variety of application scenarios in C++.