前言
本章 我们来介绍一下stl::pair模板.为什么要涉及这个东西嘞?这是因为在看LightGBM的时候经常看到pair出没。
其实pair就是一种二元关系,该关系定义了A,B两个集合的笛卡尔积
我们来看笛卡尔积的数学定义:
设存在集合A,B,我们定义集合A和B的乘积C.其中
C=(a,b),s.t.a∈A,b∈B
C=(a,b),s.t.a∈A,b∈B
,并且满足:
c1=(a1,b1)=c2=(a2,b2)
c1=(a1,b1)=c2=(a2,b2)
当仅当
a1=a2,b1=b2
a1=a2,b1=b2
。
而pair就是为了表示这种关系。
source code
#ifndef PAIR_H
#define PAIR_H
template <class T1, class T2>
struct pair {
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair() : first(T1()), second(T2()) {}
pair(const T1& a, const T2& b) : first(a), second(b) {}
#ifdef __STL_MEMBER_TEMPLATES
template <class U1, class U2>
pair(const pair<U1, U2>& p) : first(p.first), second(p.second) {}
#endif
};
template <class T1, class T2>
inline bool operator==(const pair<T1, T2>& x, const pair<T1, T2>& y) {
return x.first == y.first && x.second == y.second;
}
template <class T1, class T2>
inline bool operator<(const pair<T1, T2>& x, const pair<T1, T2>& y) {
return x.first < y.first || (!(y.first < x.first) && x.second < y.second);
}
template <class T1, class T2>
inline pair<T1, T2> make_pair(const T1& x, const T2& y) {
return pair<T1, T2>(x, y);
}
#endif
代码 很简短,就是定义了pair类以及两个构造函数,然后重载了operator以及定义了make_pair函数。
分析
1.pair是一个struct,因此里面成员的默认访问控制符为public.这意味者我们可以直接读写pair两个元素的值。
2.只定义了operator和operator<,其他<=,>=,!=都可以基于这两个符号生成。
使用
#include <stdio.h>
#include <stdlib.h>
#include <utility>
int main()
{
std::pair<int, int> p1 = { 2, 3 };
std::pair<int, int> p2 = { 1, 3 };
printf("%d %d\n", p1.first, p2.second);
printf("%d", p1 < p2);
system("pause");
return 0;
}
头文件在utility.h