Overview of pair types
Pair is a template type that contains two data values, and two types of data can be different, basically defined as follows:
Indicates that there are two types in a, the first element is type int, the second element is string, and if it is not initialized when pair is created, the default constructor is invoked to initialize it.
Pair<string, string> A ("James", "Joy");
It can also be initialized directly to the definition as above.
Because the use of pair types is cumbersome, because if you want to define multiple pair types, the typedef can simplify the declaration:
typedef pair<string, string> author;
Author Pro ("May", "Lily");
Author Joye ("James", "Joyce");
two ,the pair object operation
1, for the pair class, because it has only two elements, named First and second respectively, so directly using the ordinary point operator to access its members
Pair<string, string> A ("Lily", "Poly");
string name;
name = Pair.second;
2, the generation of new pair objects
You can use Make_pair to construct a new pair type for existing two data:
int a = 8;
string m = "James";
Pair<int, string> Newone;
Newone = Make_pair (A, m);
Third, the programming practice
Practice: Write a program that reads a series of string and int data, stores each group in a pair object, and then stores the pair objects in a 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;
}
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.