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
相关文章推荐
- c++11并发编程指南三(std::mutex 详解)
- C++ using namespace std 详解 与 命名空间的使用
- using namespace std 详解
- C++11 并发指南六( <atomic> 类型详解二 std::atomic )
- C++函数调用详解
- C++ STL std::copy 详解
- C++ using namespace std 详解
- C++11 并发指南二(std::thread 详解)
- C++11 并发指南四(<future> 详解一 std::promise 介绍)
- C++11 并发指南五(std::condition_variable 详解)
- C++11 并发指南六( <atomic> 类型详解二 std::atomic )
- c++11并发编程指南四(std::future std::promise详解)
- C++11 并发指南六( <atomic> 类型详解二 std::atomic )
- 命名空间std详解
- C++函数调用详解
- C++ using namespace std 详解
- std::ios::sync_with_stdio和tie()——给cin加速
- C++11 std::chrono库详解
- C++ using namespace std 详解
- C++17之std::optional全方位详解