C++ STL pair

来源:互联网 发布:java解析log日志文件 编辑:程序博客网 时间:2024/06/06 18:07

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);

 

1#include <iostream>
2#include <utility>
3#include <string>
4usingnamespace std;
5
6int main () {
7pair <string,double> product1 ("tomatoes",3.25);
8pair <string,double> product2;
9pair <string,double> product3;
10
11product2.first ="lightbulbs"; // type of first is string
12product2.second =0.99; // type of second is double
13
14product3 = make_pair ("shoes",20.0);
15
16cout <<"The price of "<< product1.first <<" is $"<< product1.second <<"\n";
17cout <<"The price of "<< product2.first <<" is $"<< product2.second <<"\n";
18cout <<"The price of "<< product3.first <<" is $"<< product3.second <<"\n";
19return0;
20}
其运行结果如下:
1The price of tomatoes is $3.25
2The price of lightbulbs is $0.99
3The price of shoes is $20





01 pair  vs  make_pair
02 make_pair constructs a pair object.
03 template
04 pair make_pair(T1 x, T2 y)
05 {
06     return pair(x, y);
07 }
08
09 eg:  std::pair("sn001", 12.5);
10        std::make_pair("sn001", 12.5);
11        两者效果一样。
12 倘若:std::pair("sn002", 12.6);   // 12.6's datatype is float
13         std::make_pair("sn002",12.6);  // 12.6's datatype is double
14 使用:
15         std::pair m_pairA;
16         m_pairA = std::make_pair("sn001", 12.5);
17         std::cout<<m_pairA.first<<"  "<<m_pairA.second<<std::endl;
18 结合map的简单使用:
19         std::pair m_pairA;
20         m_pairA = std::make_pair("sn001", 12.5);
21         //std::cout<<m_pairA.first<<"  "<<m_pairA.second<<std::endl;
22         std::map m_mapA;
23         m_mapA.insert(m_pairA);
24         std::map::iterator iter = m_mapA.begin();
25         std::cout<<iter->first<<"  "<<iter->second<<std::endl;
小结:
  make_pair创建的是一个pair对象。使用都很方便,针对成对出现的数据,如书的ISBN对应一个书名。
  pair是单个数据对的操作,pair是一struct类型,有两个成员变量,通过first,second来访问,用的是“.”访问。
  map是一个关联容器,里面存放的是键值对,容器中每一元素都是pair类型,通过map的insert()方法来插入元素(pair类型)。

原创粉丝点击