pair基本用法
pair<string, int> p1("hello world", 233);
cout << p1.first << " " << p1.second;
p1 = make_pair("lala", 322);
pair 其他使用
重载pair的加减运算符
// 加法
template<class Ty1,class Ty2>
inline const pair<Ty1,Ty2> operator+(const pair<Ty1, Ty2>&p1, const pair<Ty1, Ty2>&p2)
{
pair<Ty1, Ty2> ret;
ret.first = p1.first + p2.first;
ret.second = p1.second + p2.second;
return ret;
}
// 减法
template<class Ty1, class Ty2>
inline const pair<Ty1, Ty2> operator-(const pair<Ty1, Ty2>&p1, const pair<Ty1, Ty2>&p2)
{
pair<Ty1, Ty2> ret;
ret.first = p1.first - p2.first;
ret.second = p1.second - p2.second;
return ret;
}
在vector中使用
// 初始化举例
vector<pair<int, int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
// 添加新元素几种方式
// make_pair
dirs.push_back(make_pair(2,2));
// 初始化构造函数
dirs.push_back(pair<int, int>(2,2));
// 聚合初始化
dirs.push_back({2,2});
// emplace_back
dirs.emplace_back(2,2);