一、概述
pair是一种模板类型,定义在头文件utility中。(使用#include < vector >也可以包含)
pair包含两个数据成员,两个数据的类型可以不同,基本的定义如下:
pair<int, string> p;
表示p中有两个类型,第一个元素是int型的,第二个元素是string类型的,如果创建pair的时候没有对其进行初始化,则调用默认构造函数对其初始化。
pair<string, string> p("Tom", "Paul");
也可以像上面一样在定义的时候直接对其初始化。
由于pair类型的使用比较繁琐,因为如果要定义多个形同的pair类型的时候,可以使用typedef简化声明:
typedef pair<string, string> author;
author pro("May", "Lily");
author joye("James", "Joyce");
相关代码:
#include <iostream>
#include <utility>
using namespace std;
typedef pair<string, string> author;
author pro("May", "Lily");
author joye("James", "Joyce");
pair<string, string> a("James", "Joy");
int main()
{
cout<<a.first<<endl;
cout<<a.second<<endl;
cout<<pro.first<<endl;
cout<<pro.second<<endl;
return 0;
}
二、操作
1、对于pair类,由于它只有两个元素,分别名为first和second,因此直接使用普通的点操作符即可访问其成员:
pair<string, string> a("Lily", "Poly");
string name;
name = a.second;
2、生成新的pair对象
可以使用make_pair对已存在的两个数据构造一个新的pair类型:
int a = 8;
string m = "James";
pair<int, string> newone;
newone = make_pair(a, m);
相关代码:
#include <iostream>
#include <utility>
using namespace std;
//typedef pair<string, string> author;
//author pro("May", "Lily");
//author joye("James", "Joyce");
//pair<string, string> a("James", "Joy");
int main()
{
//cout<<a.first<<endl;
//cout<<a.second<<endl;
//cout<<pro.first<<endl;
//cout<<pro.second<<endl;
pair<string, string> a("Lily", "Poly");
string name;
name = a.second;
cout<<name<<endl;
int n = 8;
string m = "James";
pair<int, string> newone;
newone = make_pair(n, m);
cout<<newone.first<<endl;
cout<<newone.second<<endl;
return 0;
}
三、c++ primer 代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
pair<string, string> anon; // 包含两个字符串
pair<string, int> word_count; // 包含字符串和整数
pair<string, vector<int> > line; // 包含字符串和一个int容器
pair<string, string> author("James", "Joyce"); // 定义成员时初始化
cout << author.first << " - " << author.second << endl;
string firstBook; // 使用 . 访问和测试pair数据成员
if (author.first == "James" && author.second == "Joyce") {
firstBook = "Stephen Hero";
cout << firstBook << endl;
}
typedef pair<string, string> Author; // 简化声明一个作者pair类型
Author proust("Marcel", "Proust");
Author Joyce("James", "Joyce");
pair<string, string> next_auth;
string first, last;
while (cin >> first >> last) {
// 使用make_pair函数生成一个新pair对象
next_auth = make_pair(first, last);
// 使用make_pair函数,等价于下面这句
next_auth = pair<string, string> (first, last);
cout << next_auth.first << " - " << next_auth.second << endl;
if (next_auth.first == next_auth.second)
break; // 输入两个相等,退出循环
}
cout << "因为pair的数据成员是共有的,因而可以直接读取输入" << endl;
while (cin >> next_auth.first >> next_auth.second) {
cout << next_auth.first << " - " << next_auth.second << endl;
if (next_auth.first == next_auth.second)
break;
}
return 0;
}
结果:
James - Joyce
Stephen Hero
a b
a - b
m n
m - n
a a
a - a
因为pair的数据成员是共有的,因而可以直接读取输入
p y
p - y
p p
p - p
Process returned 0 (0x0) execution time : 68.310 s
Press any key to continue.