Pair类型概述
pair是一种模板类型,其中包含两个数据值,两个数据的类型可以不同,基本的定义如下:
pair<int, string> a;
表示a中有两个类型,第一个元素是int型的,第二个元素是string类型的,如果创建pair的时候没有对其进行初始化,则调用默认构造函数对其初始化。
pair<string, string> a("James", "Joy");
也可以像上面一样在定义的时候直接对其初始化。
由于pair类型的使用比较繁琐,因为如果要定义多个形同的pair类型的时候,可以时候typedef简化声明:
typedef pair<string, string> author;
author pro("May", "Lily");
author joye("James", "Joyce");
Pair对象的操作
-
对于pair类,由于它只有两个元素,分别名为first和second,因此直接使用普通的点操作符即可访问其成员
pair<string, string> a("Lily", "Poly");
string name;
name = pair.second;
- 生成新的pair对象
可以使用make_pair对已存在的两个数据构造一个新的pair类型:
int a = 8;
string m = "James";
pair<int, string> newone;
newone = make_pair(a, m);
#include <iostream>
#include <utility>
#include <string>
usingnamespace std;
int main (){
pair <string,double> product1 ("tomatoes",3.25);
pair <string,double> product2;
pair <string,double> product3;
product2.first ="lightbulbs"; // type of first is string
product2.second =0.99; // type of second is double
product3 = make_pair ("shoes",20.0);
cout <<"The price of "<< product1.first <<" is $"<< product1.second <<"\n";
cout <<"The price of "<< product2.first <<" is $"<< product2.second <<"\n";
cout <<"The price of "<< product3.first <<" is $"<< product3.second <<"\n";
return0;
}
其运行结果如下:
1The price of tomatoes is $3.25
2The price of lightbulbs is $0.99
3The price of shoes is $20
pair vs make_pair make_pair constructs a pair object. template pair make_pair(T1 x, T2 y) { return pair(x, y); } eg: std::pair("sn001", 12.5); std::make_pair("sn001", 12.5); 两者效果一样。 倘若:std::pair("sn002", 12.6); // 12.6's datatype is float std::make_pair("sn002",12.6); // .6's datatype is double 使用: std::pair m_pairA; m_pairA = std::make_pair("sn001", 12.5); std::cout<<m_pairA.first<<" "<<m_pairA.second<<std::endl; 结合map的简单使用: std::pair m_pairA; m_pairA = std::make_pair("sn001", 12.5); //std::cout<<m_pairA.first<<" "<<m_pairA.second<<std::endl; std::map m_mapA; m_mapA.insert(m_pairA); std::map::iterator iter = m_mapA.begin(); std::cout<<iter->first<<" "<<iter->second<<std::endl;
小结:
make_pair创建的是一个pair对象。使用都很方便,针对成对出现的数据,如书的ISBN对应一个书名。
pair是单个数据对的操作,pair是一struct类型,有两个成员变量,通过first,second来访问,用的是“.”访问。
map是一个关联容器,里面存放的是键值对,容器中每一元素都是pair类型,通过map的insert()方法来插入元素(pair类型)。