Standard library type-pair type definition is defined in the utility header file
URL: http://www.cnblogs.com/archimedes/p/cpp-pair.html.
1. Create and initialize pair
Pair contains two values. Like a container, pair is also a template type. However, unlike the previously described container, when creating a pair object, you must provide two types of names. The types of the two types do not have to be the same.
pair<string,string>anon;pair<string,int>word_count;pair<string, vector<int> >line;
You can also provide initialization for each member during the definition:
pair<string,string>author("James","Joy");
Pair type is quite tedious to use. If multiple objects of the same pair type are defined, you can use typedef to simplify the Declaration:
typedef pair<string,string> Author;Author proust("March","Proust");Author Joy("James","Joy");2. pair object operations
For the pair class, you can directly access its data members: all its members are public, named first and second respectively. You only need to use common vertex operators.
string firstBook;if(author.first=="James" && author.second=="Joy") firstBook="Stephen Hero";
3. generate a new pair object
In addition to constructors, the standard library also defines a make_pair function, which generates a new pair object from the two arguments passed to it.
pair<string, string> next_auth;string first,last;while(cin>>first>>last) { next_auth=make_pair(first,last); //...}
You can also use the following equivalent and more complex operations:
next_auth=pair<string,string>(first,last);
Since the pair data member is public, you can directly read the input as follows:
pair<string, string> next_auth;while(cin>>next_auth.first>>next_auth.last) { //...}4. programming practices
Exercise: write a program to read a series of string and int data, store each group in a pair object, and then store these pair objects in the vector container.
#include<iostream>#include<string>#include<vector>#include<utility>using namespace std;int main(){ pair<string, int>p; typedef vector< pair<string, int> > VP; VP vp; while(cin>>p.first>>p.second) { vp.push_back(make_pair(p.first,p.second)); } VP::iterator it; for(it=vp.begin(); it!=vp.end(); it++) cout<<it->first<<","<<it->second<<endl; return 0;}