[C++]STL pair

来源:互联网 发布:java解析pdf文件内容 编辑:程序博客网 时间:2024/05/18 16:18

    本文转自http://blog.csdn.net/wangran51/article/details/8853565

  

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>using namespace 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 stringproduct2.second =0.99; // type of second is doubleproduct3 = 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";return 0;}

其运行结果如下:
1The price of tomatoes is $3.25
2The price of lightbulbs is $0.99
3The price of shoes is $20


0 0
原创粉丝点击