CppDS.com

C++ 98 11 14 17 20 手册

std::tie

来自cppreference.com
< cpp‎ | utility‎ | tuple
 
 
工具库
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)
swap 与类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等字符串转换
(C++17)
(C++17)
 
 
定义于头文件 <tuple>
template< class... Types >
tuple<Types&...> tie( Types&... args ) noexcept;
(C++11 起)
(C++14 前)
template< class... Types >
constexpr tuple<Types&...> tie( Types&... args ) noexcept;
(C++14 起)

创建到其参数或 std::ignore 实例的左值引用的 tuple 。

参数

args - 构造 tuple 所用的零或更多左值参数

返回值

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

注意

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

bool result;
std::tie(std::ignore, result) = set.insert(value);

示例

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

参阅

创建一个 tuple 对象,其类型根据各实参类型定义
(函数模板)
创建转发引用tuple
(函数模板)
通过连接任意数量的元组来创建一个tuple
(函数模板)
tie 解包 tuple 时用来跳过元素的占位符
(常量)
关闭