Pair is defined in the header file utility. It is mainly used to combine two data types into one. The two data types can be the same type or different types.
Operation provided by the pair type:
pair<T1,T2> p1;pair<T1,T2> p1(v1,v2);make_pair(v1,v2);p1 < p2;p1 == p2;p.first;p.second;
1. Create and initialize:
pair<string,string> name; pair<string,vector<int>> data;
All of the above call the default constructor of the pair type to initialize the value of its members. The member Initialization is null or 0.
Initialization can also be provided during definition:
Pair <string, int> Mike ("Mike Brown", 26 );
Tip: Use typedef to simplify the Declaration
typedef pair<string,string> name; name dotcom("is","programmer");
2. Pair object operations
The two pair members, first and second, are both public members and can be accessed using the vertex OPERATOR:
string next; if (name.first == "gem" && name.second == "linux") next = name.first;
3. generate a new pair object
The make_pair function can generate a pair object. For example:
pair<string,string> next_auth; string first,last; while (cin >> first >> last){ next_auth = make_pair(first,last); }
Tip: You can directly use a standard input stream to read data into a pair object.
pair<string,string> next_auth; while (cin >> next_auth.first >> next_auth.second){...}
Pair is essentially a struct. Its two major member variables are first and second, which can be directly used. You can use Constructor (as shown above) or make_pair to initialize a pair. Generally, make_pair is used at the position where pair is required. You can directly call make_pair to generate a pair object. Another aspect of use is that pair can accept implicit type conversion to achieve higher flexibility. However, the following problems may occur: for example, there are two definitions:
pair<int, float>(1, 1.1);make_pair(1, 1.1);
The first second variable is of the float type, while the make_pair function converts all second variables to the double type. This issue requires attention in programming.
In addition, map is an associated container that stores key-value pairs. Each element in the container is of the pair type. The insert () method of map is used to insert elements (pair type ). Use in vector:
bool strict_weak_ordering(const std::pair<int,std::string>a,const std::pair<int,std::string>b) { return a.first < b.first; } int main() { using namespace std; vector<pair<int, string> > vec; vec.push_back(make_pair<int, string>(5, "hello")); vec.push_back(make_pair<int, string>(4, "hell")); vec.push_back(make_pair<int, string>(6, "hello,")); sort(vec.begin(), vec.end(), strict_weak_ordering); vector<pair<int, string> >::iterator it = vec.begin(), end = vec.end(); for(;it != end; ++it) cout<<it->second<<endl; }
Use Vector to store the PIAR type, sort the begin () of each pair type data through sort, and use the iterator to output the second () of the pair type data ().
Detailed analysis of pair type in STL