C++ 和 Java 中的 Pair 配对
\qquad 配对(Pair)。配对提供了一种方便方式来处理简单的键值关联,当我们想从方法返回两个值时特别有用。
Java
Pair类在javafx.util 包中,类构造函数有两个参数,键及对应值
Pair<Integer, String> pair = new Pair<>(1, "One");
Integer key = pair.getKey();
String value = pair.getValue();
示例描述使用Pair类实现简单Integer到String的映射。示例中getKey方法返回key对象,getValue方法返回对应值对象
应用
private Map<Pair<Integer, Integer>, Integer> map = new HashMap<>();
public NumArray(int[] nums) {
for (int i = 0; i < nums.length; i++) {
int sum = 0;
for (int j = i; j < nums.length; j++) {
sum += nums[j];
map.put(Pair.create(i, j), sum);
}
}
}
public int sumRange(int i, int j) {
return map.get(Pair.create(i, j));
}
C++
pair是将2个数据组合成一个数据,当需要这样的需求时就可以使用pair。
(1)STL中的map就是将key和value放在一起来保存。
(2)另一个应用是,当一个函数需要返回2个数据的时候,可以选择pair。
pair的构造
std::pair主要的作用是将两个数据组合成一个数据,两个数据可以是同一类型或者不同类型。例如std::pair 或者 std::pair等。pair实质上是一个结构体,其主要的两个成员变量是first和second,这两个变量可以直接使用。初始化一个pair可以使用构造函数,也可以使用std::make_pair函数,make_pair函数的定义如下:
template pair make_pair(T1 a, T2 b) { return pair(a, b); }
一般make_pair都使用在需要pair做参数的位置,可以直接调用make_pair生成pair对象。 另一个使用的方面就是pair可以接受隐式的类型转换,这样可以获得更高的灵活度。但是这样会出现如下问题:例如有如下两个定义:
std::pair(1, 1.1);
std::make_pair(1, 1.1);
其中第一个的second变量是float类型,而make_pair函数会将second变量都转换成double类型。这个问题在编程是需要引起注意。
例子
下面是一段pair与make_pair的例子程序:
#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;
}
其运行结果如下:
The price of tomatoes is $3.25
The price of lightbulbs is $0.99
The price of shoes is $20
小结:
- make_pair创建的是一个pair对象。使用都很方便,针对成对出现的数据,如书的ISBN对应一个书名。
- pair是单个数据对的操作,pair是一struct类型,有两个成员变量,通过first,second来访问,用的是“.”访问。
- map是一个关联容器,里面存放的是键值对,容器中每一元素都是pair类型,通过map的insert()方法来插入元素(pair类型)。