在补CF周赛时发现dalao用了一个 tie函数和tuple类型,表示没怎么接触,如今稍微学习记录一下。ios
tuple
即元组,能够理解为pair的扩展,能够用来将不一样类型的元素存放在一块儿,经常使用于函数的多返回值。函数
定义与初始化
tuple能够使用初始化列表进行赋值。学习
tuple<int,double,string> t3 = {1, 2.0, "3"};
std::tie:
建立左值引用的 tuple
,或将 tuple 解包为独立对象code
含左值引用的 std::tuple 对象。对象
std::tie
可用于解包 std::pair ,由于 std::tuple 拥有从 pair 的转换赋值:get
std::tie
能用于引入字典序比较到结构体,或解包 tuple :string
#include <iostream> #include <set> #include <string> #include <tuple> 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); } }; int main() { std::set<S> set_of_s; // S 为可比较小于 (LessThanComparable) S value{42, "Test", 3.14}; std::set<S>::iterator iter; bool inserted; // 解包 insert 的返回值为 iter 与 inserted std::tie(iter, inserted) = set_of_s.insert(value); if (inserted) std::cout << "Value was inserted successfully\n"; }
结果以下:it
Value was inserted successfully
std::tie会将变量的引用整合成一个tuple,从而实现批量赋值。io
int i; double d; string s; tie(i, d, s) = t3; cout << i << " " << d << " " << s << endl;
会输出4 2 3
class
以下例子摘自http://www.cplusplus.com/reference/tuple/tie/
// packing/unpacking tuples #include <iostream> // std::cout #include <tuple> // std::tuple, std::make_tuple, std::tie int main() { int myint; char mychar; std::tuple<int, float, char> mytuple; mytuple = std::make_tuple(10, 2.6, 'a'); // packing values into tuple std::tie(myint, std::ignore, mychar) = mytuple; // unpacking tuple into variables std::cout << "myint contains: " << myint << '\n'; std::cout << "mychar contains: " << mychar << '\n'; return 0; }
输出:
myint contains: 10 mychar contains: a
std::ignore介绍:
任何值都可赋给而无效果的未指定类型的对象。目的是令 std::tie 在解包 std::tuple 时做为不使用的参数的占位符使用。
解包 set.insert() 所返回的 pair ,但只保存布尔值。
#include <iostream> #include <string> #include <set> #include <tuple> int main() { std::set<std::string> set_of_str; bool inserted = false; std::tie(std::ignore, inserted) = set_of_str.insert("Test"); if (inserted) { std::cout << "Value was inserted successfully\n"; } }
结果以下:
Value was inserted successfully