std::tie:创建左值引用的 tuple
,或将 tuple 解包为独立对象
含左值引用的 std::tuple 对象。
std::tie
可用于解包 std::pair ,因为 std::tuple 拥有从 pair 的转换赋值:
std::tie
能用于引入字典序比较到结构体,或解包 tuple :
#include <iostream>
#include <string>
#include <set>
#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";
}
结果如下:
Value was inserted successfully
std::tie会将变量的引用整合成一个tuple,从而实现批量赋值。
int i; double d; string s;
tie(i, d, s) = t3;
cout << i << " " << d << " " << s << endl;
会输出4 2 3
如下例子摘自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