1 pair的应用(结构体模板)
pair是将2个数据组合成一个数据,当需要这样的需求时就可以使用pair,如stl中的map就是将key和value放在一起来保存。另一个应用是,当一个函数需要返回2个数据的时候,可以选择pair。
头文件:#include<utility>
类模板:template <class T1, class T2> struct pair
定义方法:
pair<变量类型1,变量类型2> 变量名
eg: pair<int,int>p;
.实例化
eg:pair<int,int>(3,4)//初始化一个pair,第一个成员是int,第二个成员也是int类型
对象的赋值以及make_pair()的应用:
pair<int,int> q = make_pair(3 ,4);
(1)第一种用法函数返回:
pair<int,int> func()
{
int height = 3;
int weight = 4;
return pair<int,int>(3,4);
}
int main(int argc, char *argv[])
{
pair<int, int> p = func(); //调用函数
return 0;
}
cout<<p.first<<" "<<p.second<<endl; //
(2)使用在stl map
struct student {
int height;
int weight;
};
int main(int argc, char *argv[])
{
map<int ,struct student> map1;
struct student a;
struct student b;
//错误写法 map.insert<1,a>;错误写法
map1.insert(pair<int, struct student>(1, a));//等价于 ----- map1.insert(make_pair(1, a));
cout<<map1.size()<<endl;
return 0;
}
3.pair中元素的访问(first & second):
eg:
pair<int,int> func()
{
int height = 3;
int weight = 4;
return pair<int,int>(3,4);
}
pair<int, int> p = func();
cout<<p.first<<" "<<p.second<<endl;
说到这里,有的同学应该想问,这不就是c语言的结构体吗?是的,这就是c++的结构体模板
源码:
template<class _T1, class _T2>
struct pair
{
typedef _T1 first_type; /// @c first_type is the first bound type
typedef _T2 second_type; /// @c second_type is the second bound type
_T1 first; /// @c first is a copy of the first object
_T2 second; /// @c second is a copy of the second object、
....
.......
对了什么叫结构体模板,哈哈,敬请关注!!!