赞
踩
tuple的作用
C++ 中的 std::tuple
是标准库提供的一个容器,它可以存储任意数量、任意类型的元素。相比于只能存储两个元素的 std::pair
,std::tuple
允许你创建包含更多元素的数据结构,并且这些元素可以是不同类型的。
获取tuple的值 std::get<index>(myTuple)
来访问指定索引位置的元素。索引从0开始。
例如:int intValue = std::get<0>(myTuple); // 访问第一个元素(int 类型)
std::string strValue = std::get<1>(myTuple); // 访问第二个元素(std::string 类型)
double dblValue = std::get<2>(myTuple); // 访问第三个元素(double 类型)
get<x> 是第几个元素,注意第一个元素是从0开始的
- #include <iostream>
- #include <string>
- #include <tuple>
- using namespace std;
-
- int main() {
- // 定义一个 tuple 存储整数、字符串和浮点数
- tuple<int,string, double> myTuple(42, "hi!", 3.14);
- cout<<get<0>(myTuple)<<get<1>(myTuple)<<get<2>(myTuple)<<endl;
- // 或者通过构造函数参数列表初始化
- tuple<int,string, double> anotherTuple = make_tuple(42, "hi!", 3.14);
- cout<<get<0>(anotherTuple)<<get<1>(anotherTuple)<<get<2>(anotherTuple)<<endl;
- return 0;
- }
- std::size_t size = std::tuple_size_v<decltype(myTuple)>; // 获取元组大小
- using IntType = typename std::tuple_element<0, decltype(myTuple)>::type; // 获取第一个元素的类型
- std::tuple<int, std::string, double> copyOfTuple(myTuple); // 拷贝构造
- copyOfTuple = anotherTuple; // 赋值操作
-
- if (myTuple == anotherTuple) { // 使用内置的等于运算符进行比较
- // ...
- }
- #include <iostream>
- #include <string>
- #include <tuple>
- using namespace std;
-
- int main() {
- // 定义一个 tuple 存储整数、字符串和浮点数
- tuple<int,string, double> myTuple(42, "hi!", 3.14);
- cout<<get<0>(myTuple)<<get<1>(myTuple)<<get<2>(myTuple)<<endl;
- // 修改里面的元素
- get<0>(myTuple) = 50;
- get<1>(myTuple) = "hello";
- get<2>(myTuple) = 3.1415;
- cout<<get<0>(myTuple)<<get<1>(myTuple)<<get<2>(myTuple)<<endl;
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。