我是靠谱客的博主 英勇大雁,这篇文章主要介绍std::tuple, std::pair, std::tie 快速掌握,现在分享给大家,希望可以做个参考。

tuple是可以存异构元素的容器,比如可以在一个容器中同时存储int、string、bool等。
作为对比,vector只能存储同类型的元素。tuple可做作为struct的一种更简洁高效的替代。

使用tuple可以实现让一个函数返回多个不同类型的值。

std::tuple<double, char, std::string> get_student()
{
    return std::make_tuple(3.8, 'A', "Lisa Simpson");
}

pair则相当于tuple的特殊情况,即只能有两个元素。并且提供了类似于first、second等易于使用的成员。

std::pair <int,double> product1;
product1 = std::make_pair(10, 0.99); 

std::pair <std::string,double> product2 ("tomatoes",2.30);

tie函数可以用于接收函数返回的tuplepair,将其解包给对应的变量,如下例:

double gpa1;
char grade1;
std::string name1;
std::tie(gpa1, grade1, name1) = get_student(); // 函数定义见第一个例子

原理是tie构造了一个存引用的tuple,函数返回的tuplepairtie构造的tuple赋值,可以实现对各引用逐个赋值的功能。

// tie的原型
template< class... Types >
std::tuple<Types&...> tie( Types&... args ) noexcept; // (since C++11 until C++14)

template< class... Types >
constexpr std::tuple<Types&...> tie( Types&... args ) noexcept; // (since C++14)

参考资料:
https://en.cppreference.com/w/cpp/utility/tuple
https://en.cppreference.com/w/cpp/utility/pair
https://cplusplus.com/reference/utility/pair/pair/
https://en.cppreference.com/w/cpp/utility/tuple/tie

最后

以上就是英勇大雁最近收集整理的关于std::tuple, std::pair, std::tie 快速掌握的全部内容,更多相关std::tuple,内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(124)

评论列表共有 0 条评论

立即
投稿
返回
顶部