C++高级_pair对组的使用_STL标准模板库

pair对组的使用

pair译为对组,可以将两个值视为一个单元

将两个值使用为一个单元的情况,就可以使用pairs。在c++的标准模板库中,很多模板容器的实现都使用了pairs,例如:mapmutimap等键值对组合结构。

类模板:template <class T1, class T2> struct pair

参数:T1是第一个值的数据类型,T2是第二个值的数据类型。

功能:pair将一对值组合成一个值,这一对值可以具有不同的数据类型(T1和T2),两个值可以分别用pair的两个公有函数first和second访问

pair.first 是pair里面的第一个值,是T1类型。

pair.second 是pair里面的第二个值,是T2类型。

//默认构造函数
pair<int, double> p1;  //使用默认构造函数
pair<int, double> p2(1, 2.4);  //用给定值初始化
pair<int, double> p3(p2);  //拷贝构造函数

//通过first和second访问两个元素
pair<int, double> p1;  //使用默认构造函数
p1.first = 1;
p1.second = 2.5;
cout << p1.first << ' ' << p1.second << endl;

//输出结果:1 2.5

赋值operator =

1)利用make_pair

pair<int, double> p1;
p1 = make_pair(1, 1.2);

(2)变量间赋值:

pair<int, double> p1(1, 1.2);
pair<int, double> p2 = p1;

代码示例演示:

//pair:对组,可以将两个值(first,second)视为一个单元(pair),是个模板类。对于map/multimap,就是用pairs来管理value/key的成对元素。任何函数需要回传两个值,也需要pair
#include <utility>
#include <string>
#include <conio.h>
#include<iostream>
using namespace std;    
void test0()
{   
	pair<string,double> product1("tomatoes",3.25);//定义一个组单元
	pair<string,double> product2;
	pair<string,double> product3;
	product2.first="lightbulbs";
	product2.second=0.99;//设置pair的first,second数据
	product3=make_pair("shoes",20.0);//make_pair是个模板函数,返回pair
	cout<<"the price of "<<product1.first<<" is $"<<product1.second<<endl;//获取pair的first,second的数据
	cout<<"the price of "<<product2.first<<" is $"<<product2.second<<endl;
	cout<<"the price of "<<product3.first<<" is $"<<product3.second<<endl;
} 
void Test(char h)
{
	cout<<"press key===="<<h<<endl;
	switch(h)
	{ 
	case '0':  test0();break; 
	case 27:
	case 'q':exit(0);break; 
	default:cout<<"default "<<h<<endl;break;
	}
}
void main()
{
	while(1)
	{
		Test(getch());
	} 
}
庄朋龙
庄朋龙

一个爱生活的技术菜鸟

留下评论