您的位置:首页 > 编程语言 > C语言/C++

C++中pair的用法

2015-08-05 18:19 387 查看
pair的类型:

pair 是 一种模版类型。每个pair 可以存储两个值。这两种值无限制。也可以将自己写的struct的对象放进去

pair<string,int> p;

pair<int ,int > p;

pair<double,int> p;

都可以。。。


应用:如果一个函数有两个返回值 的话,如果是相同类型,就可以用数组返回,如果是不同类型,就可以自己写个struct ,但为了方便就可以使用 c++ 自带的pair ,返回一个pair,其中带有两个值。除了返回值的应用,在一个对象有多个属性的时候 ,一般自己写一个struct ,如果就是两个属性的话,就可以用pair 进行操作。。。

应用pair 可以省得自己写一个struct 。。。如果有三个属性的话,其实也是可以用的pair 的 ,极端的写法
pair <int ,pair<int ,int > >
写法极端。(后边的两个 > > 要有空格,否则就会是 >> 位移运算符)

例子:看懂这个例子,应该就理解的差不多了

#include <utility>
#include <iostream>
using namespace std;
int main()
{
pair<int,int> m_pair(20,2);

typedef pair<int,int> Contain;
Contain Con1(10,1);
Contain Con2(30,3);

if(20==m_pair.first && 2==m_pair.second)
{
cout<<"m_pair_first is "<<m_pair.first<<" AND m_pair_last is "<<m_pair.second<<endl;
}

cout<<"Con1_first is "<<Con1.first<<" AND Con1_last is "<<Con1.second<<endl;
cout<<"Con2_first is "<<Con2.first<<" AND Con2_last is "<<Con2.second<<endl;

cout<<endl<<endl;

int first=0,last=0;
cout<<"Input first"<<endl;
cin>>first;
cout<<"Input last"<<endl;
cin>>last;

pair<int,int> prInput=make_pair(first,last);            //make_pair
cout<<"prInput_first is: "<<prInput.first<<endl;
cout<<"prInput_last is: "<<prInput.second<<endl;

system("pause");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ pair