本文主要是C++语言中的一些tricks或不常见但有用的语法记录,边学边更新。
1、tie
基本概念
std::pair
即二元组,可以将不同的2个元素放在一起。
std::tuple
即三元组,可以理解为pair的扩展,可以用来将不同类型的三个元素存放在一起,常用于函数的多返回值。
std:pair<int, string> mypair;
mypair = std::make_pair(10, "hello"); // packing values into pair
std::tuple<int, float, char> mytuple;
mytuple = std::make_tuple(10, 2.6, 'a'); // packing values into tuple
std::tie
创建左值引用的 tuple
,或将 元组 解包为独立对象,返回含左值引用的 对应元组 对象。
用处:
1、结构体比较
struct S {
int n;
std::string s;
float d;
bool operator<(const S& rhs) const {
// 比较 n 与 rhs.n,
// 然后为 s 与 rhs.s,
// 然后为 d 与 rhs.d
return std::tie(n, s, d) < std::tie(rhs.n, rhs.s, rhs.d);
}
};
2、解构结构体,得到每个具体的元素值
int i;
double d;
string s;
tie(i, d, s) = t3;
cout << i << " " << d << " " << s << endl;
3、利用占位符std::ignore
,得到部分元素的值
std::ignore
介绍:任何值均可赋给而无效果的未指定类型的对象。目的是令 std::tie 在解包 std::tuple 时作为不使用的参数的占位符使用。
std::tie(myint, std::ignore, mychar) = mytuple; // unpacking tuple into variables