pair 的使用

pair<T1,T2> p1 创建一个空的pair对象,它的俩个元素分别是T1,T2类型,采用了值的初始化
pair<T1,T2> p1(v1,v2) 创建一个pair对象,他的俩个元素分别是T1,T2类型,first是v1 second 是v2
make_pair(v1,v2) 以v1,v2创建一个新的pair对象
p1<p2 遵循字典次序,如果p1,first<p1.first或者!(p2.first<p1.first)&&p1.second<p2.second 则返回ture
p1==p2 p1和p2的成员first和second依次相等
p.first 返回p中名为first的(公有)数据成员
p.second 返回p中名为second的(公有)数据成员
pair<string,sting>p;

pair<stirng,int>p;

pair<stirng,vector<int> >p;

代码案例输入:

#include<bits/stdc++.h>
#include<utility>//pair在头文件utility中
using namespace std;
int main()
{
    pair<string,string>s;
    string first,last;
    while(cin>>first>>last)
    {
        s=make_pair(first,last);//调用make_pair()函数生成一个新的pair对象
        cout<<s.first<<"   fsf   "<<s.second<<endl;
    }
    pair<string,string>s1;
    while(cin>>s1.first>>s1.second)//因为pair的数据成员是公有的,所以可以直接的读取
    {
        cout<<s1.first<<endl;
        cout<<s1.second<<endl;
    }
    return 0;
}

代码案例:编写程序读入一系列string和int 型数据,将每一组存储在一个pair对象中,然后将这些pair对象存储在vectot容器中

#include<iostream>
#include<utility>
#include<vector>
using namespace std;
int main()
{
    vector<pair<string,int> >s;
    pair<string ,int>p;
    string s1;
    int p1;
    for(int i=0;i<3;i++)
    {
        cin>>s1>>p1;
        p=make_pair(s1,p1);
        s.push_back(p);
    }
    vector<pair<string,int> >::iterator it;
    for(it=s.begin();it!=s.end();++it)
    {
        cout<<it->first<<"  "<<it->second<<endl;
    }
    return 0;
}

学习pari是为了更好的学习map 和 set

可能还会学习multimap和multiset

猜你喜欢

转载自blog.csdn.net/wchenchen0/article/details/81012660
今日推荐