C++ STL pair


介绍

p a i r pair pair是一种能将两个 v a l u e value value看作一个单元的类,其中map ,multimap , unordered_map , unorderd_multimap就是用 p a i r pair pair来管理他 k e y / v a l u e key/value key/value存在的方式。
p a i r pair pair定义在<utility>里面,不过不用担心每一次都要声明,因为在namespace std里面就有引用这个文件。

事实上, p a i r pair pair并不是一个 c l a s s class class,而是一个 s t r u c t struct struct。所以他里面所有的东西都可以访问:

namespace std
{
	template<typename T1,typename T2>
	struct pair{
		// member
		T1 first;
		T2 second;
		...
	};
}

操作函数

E x a m p l e \mathbf{Example} Example

#include<iostream>

using namespace std;

//输出一个两个元素类型为T1和T2的pair
template<typename T1,typename T2>
void print(pair<T1,T2> p)
{
    //p.first访问第一个元素
    //p.second访问第二个元素
    cout<<"("<<p.first<<","<<p.second<<")"<<endl;
    return;
}

int main()
{
	pair<int,int> p1;		        //声明一个两个元素都为int的pair
	pair<int,int> p2(4,5);	        //声明一个两个元素都为int,初始值为4和5的pair
    pair<int,int> p3(p2);           //声明一个两个元素都为int,初始值为p2的pair
    print(p1);
    print(p2);
    print(p3);
    cout<<(p2==p3)<<endl;           //输出p2是否等于p3
    cout<<(p2>p1)<<endl;            //输出p2是否大于p1
    cout<<(p2<=p1)<<endl;           //输出p2是否小于等于p1
    swap(p1,p2);                    //交换p1,p2的数据
    print(p1);
    print(p2);
    p2=make_pair(114514,1919810);   //make_pair返回一个pair,带有114514和1919810的类型和数值
    print(p2);
}

输出为

(0,0)
(4,5)
(4,5)
1
1
0
(4,5)
(0,0)
(114514,1919810)

上面就是 p a i r pair pair的基本操作,下面我们来练习一下。


P r a c t i c e \mathbf{Practice} Practice

#include<bits/stdc++.h>

using namespace std;

//注意:pair是可以套pair的!
void setBook(pair<int,pair<int,string> > &s)
{
    s.first=3;
    s.second.first=4;
    s.second.second="World";
    return;
}

int main()
{
    pair<int,pair<int,string> > s,s1;
    s.first=1;
    s.second=make_pair(2,"Hello");
    cout<<s.first<<endl;
    cout<<s.second.first<<endl;
    cout<<s.second.second<<endl;
    setBook(s1);
    cout<<s1.first<<endl;
    cout<<s1.second.first<<endl;
    cout<<s1.second.second<<endl;
    pair<int,int> res;
    res=make_pair(s.first+s1.first,s.second.first+s1.second.first);
    cout<<res.first<<endl;
    cout<<res.second<<endl;
}

输出我会放在文章的最下面,建议读者自己先模拟一下,再看结果。


练习题目

下面给大家一些练习的题目,有兴趣的同学可以去做一下。
网站:51nod


Answer

T h e   o u t p u t   o f   P r a c t i c e \mathbf{The\ output\ of\ Practice} The output of Practice

1
2
Hello
3
4
World
4
6
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值