您的位置:首页 > 编程语言 > C语言/C++

C++函数:std::tie 详解

2020-12-02 20:19 1176 查看

在补CF周赛时发现dalao用了一个 tie函数和tuple类型,表示没怎么接触,现在稍 1044 微学习记录一下。

tuple
即元组,可以理解为pair的扩展,可以用来将不同类型的元素存放在一起,常用于函数的多返回值。

定义与初始化
tuple可以使用初始化列表进行赋值。

tuple<int,double,string> t3 = {1, 2.0, "3"};

std::tie:
创建左值引用的
tuple
,或将 tuple 解包为独立对象

返回值

含左值引用的 std::tuple 对象。

注意

std::tie
可用于解包 std::pair ,因为 std::tuple 拥有从 pair 的转换赋值

示例

std::tie
能用于引入字典序比较到结构体,或解包 tuple :

#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";
}

结果如下:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: