前言
本篇继续学习C++,STL的pair和tuple类。
pair
pair
类型在utility头文件中,用于把两个数据组成一对,使用pair就能让函数间接返回两个值。C++中的pair
类似于python中的[a, b]
。
可以通过构造函数或者utility
头文件中的make_pair
函数创建pair
对象,可以直接访问pair
对象的first, second
成员,也可以使用>,<,=
比较同类型的pair
对象。(首先比较first成员,如果相等再比较second成员)
可以使用std::tie()
函数解包pair
对象。
示例:
#include <cstdio>
#include <iostream>
#include <utility>
#include <tuple>
using namespace std;
pair<int, double> func(int a, int b){
return pair<int, double>(a, b);
}
int main(){
pair<int, double> p1(2, 3.3);
cout << p1.first <<" " << p1.second << endl; // 2 3.3
pair<int, double> p2 = make_pair(3, 2.2);
cout << (p1 < p2) << endl; // 1
int a, b;
tie(a, b) = func(4, 5);
cout << a <<" " << b <<endl; // 4 5
return 1;
}
}
另外,pair
中的数据类型也可以是指针,引用。
tuple
C++11引入了tuple
类型将多个数据组成一组,可以说pair
是tuple
的特例。
tuple
中的元素类型也能是指针和引用,tuple
头文件中定义了非成员函数make_tuple
,也重载了>, <, ==, =
等运算符。
因为不同的tuple
类实例可以包含不同数量的元素,因此没有pair
类似的first, second
成员。访问tuple
元素必须使用std::get
函数,其用法是std::get<index>(tuple object)
,提取元素位置是在编译时确定的(类似数组长度),因此索引index
必须是一个常量表达式,否则将报error: the value of 'i' is not usable in a constant expression
。
也可以使用std::tie()
解包tuple
对象。
示例:
tuple<int, double, char> t1(1, 2.2, 'c');
tuple<int, double, char> t2 = make_tuple(3, 4.4, 'f');
std::cout << (t2 > t1) <<endl; // 1
std::cout << std::get<0>(t2) <<endl; // 3