c++ 疑难杂症(7) std::tuple
ztj100 2025-01-21 23:12 13 浏览 0 评论
td::tuple 是 C++ 标准库中的一个模板类,C++11引入, 它用于创建一个固定大小的异质容器,其中可以存储不同类型的对象。std::tuple 提供了一种方便的方式来组合不同类型的对象到一个单一的实体中,而无需创建一个新的结构体或类。std::tuple 通常用于函数返回多个值,或者作为一种通用的容器来存储不同类型的数据。
1. 介绍
1.1 定义
template <class... _Types>
class tuple;
1.2 成员函数
(构造函数) | 构造新的 tuple (公开成员函数) |
operator= | 赋值一个 tuple 的内容给另一个 (公开成员函数) |
swap | 交换两个 tuple 的内容 (公开成员函数) |
1.3 非成员函数
make_tuple(C++11) | 创建一个 tuple 对象,其类型根据各实参类型定义 (函数模板) |
tie(C++11) | 创建左值引用的 tuple,或将 tuple 解包为独立对象 (函数模板) |
forward_as_tuple(C++11) | 创建转发引用的 tuple (函数模板) |
tuple_cat(C++11) | 通过连接任意数量的元组来创建一个tuple (函数模板) |
std::get(std::tuple)(C++11) | 元组式访问指定的元素 (函数模板) |
operator== | 按字典顺序比较 tuple 中的值 (函数模板) |
operator<=> (C++20) | 按字典顺序比较 tuple 中的值 (函数模板) |
std::swap(std::tuple)(C++11) | 特化 std::swap 算法 (函数模板) |
1.3 辅助类
std::tuple_size(C++11) | 在编译时获得 tuple 的大小 (类模板特化) |
std::tuple_element(C++11) | 获得指定元素的类型 (类模板特化) |
std::uses_allocator(C++11) | 特化 std::uses_allocator 类型特征 (类模板特化) |
std::basic_common_reference(C++23) | 确定二个 tuple 的共同引用类型 (类模板特化) |
std::common_type(C++23) | 确定二个 tuple 的共同类型 (类模板特化) |
ignore(C++11) | 用 tie 解包 tuple 时用来跳过元素的占位符 (常量) |
2. 示例
2.1 创建
#include<iostream>
#include <utility>
int main() {
class A {
int val = 0;
public:
A(int x) : val(x) {
std::cout << "A(int x) : " << val <<std::endl;
}
A(std::string str, int x) : val(x) {
std::cout << "A(std::string str, int x) : " << val << std::endl;
}
};
//直接初始化
{
std::tuple<int, std::string> x(1, "1234");
std::tuple<A, std::string> y(1, "1234");
}
//std::make_tuple
{
auto x = std::make_tuple<int, std::string>(1, "123");
auto y = std::make_tuple(A(2), "string", 0.1f);
auto z = std::make_tuple(std::string(""), A("", 3), 2);
std::tuple<A, float> h = std::make_tuple(4, 9);
}
//创建空的元组然后赋值
{
//std::tuple<A, std::string, int> x;
//错误,这里会调用A、std::string、int的默认构造函数,
//而A没有定义默认构造函数。
//可以对A添加默认构造函数:
//A(){} 或 A(int x = 0)
std::tuple<std::string, int> x;
std::get<0>(x) = "hello";
std::get<1>(x) = 999;
//std::tuple<std::string, int> x();
//这也是错误的, 它会调用创建一个空的tuple
//推测是实例化了
// template <> class tuple<> { // empty tuple
}
//std::tuple_cat
{
auto x = std::make_tuple(1, 0.3);
std::tuple<std::string, A> y("hello", 20);
auto z = std::tuple_cat(x, y);
//z元素个数
std::cout << std::tuple_size<decltype(z)>::value << std::endl;
std::cout << std::tuple_size_v<decltype(z)> << std::endl;
}
//other
{
A a(10);
std::string b("hello");
auto x = std::make_tuple(std::ref(a), std::ref(b));
auto y = std::tie(a, b);
//注意里面的元素只是引用而已, 随a、b改变
b = "world";
std::cout << "x: " << std::get<1>(x) << std::endl;
std::cout << "tie: " << std::get<1>(y) << std::endl;
//std::forward_as_tuple
auto func = [](std::tuple<A, std::string>&& tt) {
std::cout <<"lambda: " << std::get<1>(tt) << std::endl;
};
func(std::forward_as_tuple(a, b));
//operator=
auto z = x;
}
return 0;
}
2.2 函数
#include<iostream>
#include <utility>
int main() {
//打印输出
auto printf_tuple = [](const char* str,
std::tuple<int, std::string, double>& x) {
std::cout << str << " : 0=" << std::get<0>(x);
std::cout <<" 1=" << std::get<1>(x);
std::cout << " 2=" << std::get<2>(x) << std::endl;
};
//operator= operator==
auto t = std::make_tuple(10, std::string("hello"), 0.3);
std::tuple<int, std::string, double> t2(10, "hello", 0.3);
auto t3(t2);
auto t4 = t2;
if (t == t2 && t == t4) {
std::cout << "same" << std::endl;
}
//std::tuple_size
int size = std::tuple_size<decltype(t)>();
std::cout << size << std::endl;
//std::get
for (int i = 0; i < size; i++) {
//std::get<i>(t);
//错误,编译时期展开,所以i要常量
}
std::cout << "0=" << std::get<0>(t);
std::cout << " 1=" << std::get<1>(t);
std::cout << " 2=" << std::get<2>(t) << std::endl;
//swap std::swap
std::get<0>(t4) = 100;
std::get<1>(t4) = "world";
std::get<2>(t4) = 0.9;
t4.swap(t2);
printf_tuple("t2", t2);
printf_tuple("t4", t4);
std::swap(t2, t4);
printf_tuple("t2", t2);
printf_tuple("t4", t4);
//std::tie 创建
int x = 10;
std::string y("std::tie");
double z = 0.3;
auto t5 = std::tie(x, y, z);
//t5 = std::tuple<int&, std::string&, double&>
//std::tie 解包
//std::ignore
std::tie(x, std::ignore, z) = t;
std::cout << "x=" << x;
std::cout << " z=" << z<<std::endl;
//std::tuple_element
std::tuple_element<0, std::tuple<bool, int>>::type v1 = false;
std::tuple_element<0, std::tuple<bool, int>>::type v2 = 100;
return 0;
}
2.3 场景
高级场景还是应用于模板元编程,不讨论。
普通场景就是减少结构体或类的应用:
- 返回值 与 参数
#include<iostream>
#include <utility>
std::tuple<bool, int, std::string> Ret1() {
return std::make_tuple(true, 10, std::string("Ret1"));
}
decltype(auto) Ret2() {
return std::make_tuple(true, 10, std::string("Ret1"));
}
auto Ret3(std::tuple<bool, int, std::string>&& arg) {
return arg;
}
std::tuple<bool, int, std::string>&& Ret4(std::tuple<bool, int, std::string>&& arg) {
return std::forward<std::tuple<bool, int, std::string>>(arg);
}
int main() {
auto r1 = Ret1();
auto r2 = Ret2();
if (r1 == r2) {
std::cout << "r1=r2 same" << std::endl;
}
auto r3 = Ret3(std::move(r2));
auto&& r4 = Ret4(std::move(r3));
//相当于
//std::tuple<bool, int, std::string>&& r4 = std::move(r3);
auto r5 = Ret4(std::move(r4));
return 0;
}
- 与容器结合
#include<iostream>
#include <utility>
#include <vector>
#include <map>
int main() {
using TUPLE = std::tuple<int, double, std::string>;
//vector
std::vector<TUPLE> vec{ {1, 0.1, "str0.1"}, {2, 0.2, "str0.2"} };
vec.emplace_back(3, 0.3, "str0.3");
vec.push_back(std::make_tuple(4, 0.4, std::string("str0.4")));
for (auto& elem : vec) {
std::cout << "0=" << std::get<0>(elem);
std::cout << " 1=" << std::get<1>(elem);
std::cout << " 2=" << std::get<2>(elem) << std::endl;
}
//map
std::map<int, TUPLE> map({ {1, {1, 0.1, "str0.1"}}, {2, {2, 0.2, "str0.2"}} });
map.insert({ { 3, {3,0.3,"str0.3"} }, { 4, {4,0.4,"str0.4"} } });
map.emplace(5, std::make_tuple(5, 0.5, std::string("str0.5")));
std::cout << "\n\n" << std::endl;
for (auto& elem : map) {
std::cout << "0=" << std::get<0>(elem.second);
std::cout << " 1=" << std::get<1>(elem.second);
std::cout << " 2=" << std::get<2>(elem.second) << std::endl;
}
return 0;
}
- 与智能指针结合
#include<iostream>
#include <utility>
#include <list>
#include <memory>
int main() {
using TUPLE = std::tuple<int, double, std::string>;
//被指针包含
std::shared_ptr<TUPLE> x(new TUPLE(1, 0.1, "1111"));
x = std::make_shared<TUPLE>(2, 0.2, "2222");
//tuple包含指针
using TUPLE_01 = std::tuple<int, std::shared_ptr<std::string>>;
TUPLE_01 a;
{
TUPLE_01 b(100, std::make_shared<std::string>("hi"));
a = b;
}
std::cout << std::get<1>(a)->c_str() << std::endl;
//list and std::shared_ptr
std::list<std::shared_ptr<TUPLE>> lst;
std::shared_ptr<TUPLE> ptr(new std::tuple(1, 0.1, std::string("str0.1")));
lst.emplace_back(ptr);
lst.push_back(std::make_shared<TUPLE>(2, 0.2, "str0.2"));
lst.insert(lst.end(), std::make_shared<TUPLE>(3, 0.3, "str0.3"));
for (auto& elem : lst) {
std::cout << "0=" << std::get<0>(*elem.get());
std::cout << " 1=" << std::get<1>(*elem.get());
std::cout << " 2=" << std::get<2>(*elem.get()) << std::endl;
}
return 0;
}
- 与函数调用
#include <iostream>
#include <utility>
template <typename Func, typename Tuple>
auto apply_impl(Func&& f, Tuple&& t){
return std::apply(std::forward<Func>(f), std::forward<Tuple>(t));
}
template <typename Func, typename... Args>
auto perfect_forward_apply(Func&& f, Args&&... args){
return apply_impl(std::forward<Func>(f), \
std::forward_as_tuple(std::forward<Args>(args)...));
}
void test_01(int a, double b) {
std::cout << "test_01(" << a \
<< "," << b << ")" << std::endl;
}
int main()
{
int a = 42;
double b = 3.14;
perfect_forward_apply(test_01, a, b);
std::apply(test_01, std::forward_as_tuple(a, b));
auto lamdba_01 = [](int x, const char* y) {
std::cout << "lamdba_01(" << x << ", " << y << ")\n";
return x * 2;
};
perfect_forward_apply(lamdba_01, 100, "hello world!");
std::apply(lamdba_01, std::forward_as_tuple(100, "hello world"));
std::invoke(lamdba_01, 100, "hello world!");
return 0;
}
小言解析:
这段C++代码主要展示了如何使用std::apply、std::forward_as_tuple以及自定义的perfect_forward_apply函数来调用函数或lambda表达式,并将参数完美转发给它们。
首先,代码定义了两个模板函数:apply_impl和perfect_forward_apply。
- apply_impl函数接收一个函数f和一个元组t,然后使用std::apply来调用函数f并将元组t中的元素作为参数传递给f。std::apply是一个函数模板,它接受一个可调用对象和一个元组,并使用元组中的元素作为参数来调用该对象。
- perfect_forward_apply函数则是一个便利函数,它接收一个函数f和一系列参数args,然后使用std::forward_as_tuple将这些参数打包成一个元组,并调用apply_impl来应用这个函数和元组。std::forward_as_tuple是一个函数模板,它生成一个元组,并将参数完美转发给元组。
test_01函数是一个简单的函数,它接受一个int和一个double作为参数,并将它们打印到标准输出。
在main函数中,代码首先创建了两个变量a和b,然后使用perfect_forward_apply和std::apply来调用test_01函数,并将a和b作为参数传递给它。
接下来,代码定义了一个lambda表达式lamdba_01,它接受一个int和一个const char*作为参数,并将它们打印到标准输出,然后返回x的两倍。然后,代码再次使用perfect_forward_apply、std::apply和std::invoke来调用这个lambda表达式,并传递相应的参数。
注意,这里使用了std::forward来完美转发参数。完美转发意味着保持参数的原始类型(例如,lvalue或rvalue)和值类别(例如,const或非const)不变地传递给函数或lambda表达式。这对于避免不必要的拷贝和保持代码的通用性非常重要。
最后,main函数返回0,表示程序正常结束。
3. 源码探索
实现比较有意思, 类似于套娃。
参考标准文档std::tuple - cppreference.com
就不展开解析了, 参见这篇文章
<C++中VS2019下STL的std::tuple元组深入剖析>https://zhuanlan.zhihu.com/p/397720700
相关推荐
- 使用 Pinia ORM 管理 Vue 中的状态
-
转载说明:原创不易,未经授权,谢绝任何形式的转载状态管理是构建任何Web应用程序的重要组成部分。虽然Vue提供了管理简单状态的技术,但随着应用程序复杂性的增加,处理状态可能变得更具挑战性。这就是为什么...
- Vue3开发企业级音乐Web App 明星讲师带你学习大厂高质量代码
-
Vue3开发企业级音乐WebApp明星讲师带你学习大厂高质量代码下栽课》jzit.top/392/...
- 一篇文章说清 webpack、vite、vue-cli、create-vue 的区别
-
webpack、vite、vue-cli、create-vue这些都是什么?看着有点晕,不要怕,我们一起来分辨一下。...
- 超赞 vue2/3 可视化打印设计VuePluginPrint
-
今天来给大家推荐一款非常不错的Vue可拖拽打印设计器Hiprint。引入使用//main.js中引入安装import{hiPrintPlugin}from'vue-plugin-...
- 搭建Trae+Vue3的AI开发环境(vue3 ts开发)
-
从2024年2025年,不断的有各种AI工具会在自媒体中火起来,号称各种效率王炸,而在AI是否会替代打工人的话题中,程序员又首当其冲。...
- Vue中mixin怎么理解?(vue的mixins有什么用)
-
作者:qdmryt转发链接:https://mp.weixin.qq.com/s/JHF3oIGSTnRegpvE6GSZhg前言...
- Vue脚手架安装,初始化项目,打包并用Tomcat和Nginx部署
-
1.创建Vue脚手架#1.在本地文件目录创建my-first-vue文件夹,安装vue-cli脚手架:npminstall-gvue-cli安装过程如下图所示:创建my-first-vue...
- 新手如何搭建个人网站(小白如何搭建个人网站)
-
ElementUl是饿了么前端团队推出的桌面端UI框架,具有是简洁、直观、强悍和低学习成本等优势,非常适合初学者使用。因此,本次项目使用ElementUI框架来完成个人博客的主体开发,欢迎大家讨论...
- 零基础入门vue开发(vue快速入门与实战开发)
-
上面一节我们已经成功的安装了nodejs,并且配置了npm的全局环境变量,那么这一节我们就来正式的安装vue-cli,然后在webstorm开发者工具里运行我们的vue项目。这一节有两种创建vue项目...
- .net core集成vue(.net core集成vue3)
-
react、angular、vue你更熟悉哪个?下边这个是vue的。要求需要你的计算机安装有o.netcore2.0以上版本onode、webpack、vue-cli、vue(npm...
- 使用 Vue 脚手架,为什么要学 webpack?(一)
-
先问大家一个很简单的问题:vueinitwebpackprjectName与vuecreateprojectName有什么区别呢?它们是Vue-cli2和Vue-cli3创建...
- vue 构建和部署(vue项目部署服务器)
-
普通的搭建方式(安装指令)安装Node.js检查node是否已安装,终端输入node-v会使用命令行(安装)npminstallvue-cli-首先安装vue-clivueinitwe...
- Vue.js 环境配置(vue的环境搭建)
-
说明:node.js和vue.js的关系:Node.js是一个基于ChromeV8引擎的JavaScript运行时环境;类比:Java的jvm(虚拟机)...
- vue项目完整搭建步骤(vuecli项目搭建)
-
简介为了让一些不太清楚搭建前端项目的小白,更快上手。今天我将一步一步带领你们进行前端项目的搭建。前端开发中需要用到框架,那vue作为三大框架主流之一,在工作中很常用。所以就以vue为例。...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- 使用 Pinia ORM 管理 Vue 中的状态
- Vue3开发企业级音乐Web App 明星讲师带你学习大厂高质量代码
- 一篇文章说清 webpack、vite、vue-cli、create-vue 的区别
- 超赞 vue2/3 可视化打印设计VuePluginPrint
- 搭建Trae+Vue3的AI开发环境(vue3 ts开发)
- 如何在现有的Vue项目中嵌入 Blazor项目?
- Vue中mixin怎么理解?(vue的mixins有什么用)
- Vue脚手架安装,初始化项目,打包并用Tomcat和Nginx部署
- 新手如何搭建个人网站(小白如何搭建个人网站)
- 零基础入门vue开发(vue快速入门与实战开发)
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- node卸载 (33)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- exceptionininitializererror (33)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)