std::tuple、std::pair用法记录

本文介绍了C++中std::pair和std::tuple的使用,包括初始化、赋值、解包、复制以及与std::map的交互。示例代码展示了如何通过构造函数、make_pair、tie和StructuredBinding来声明和初始化pair与tuple,以及如何获取和操作它们的元素。此外,还提到了tuple的数量获取、拼接和apply函数的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

std::pair

Microsoft C++ pair 结构

int main( )
{
   using namespace std;

   pair <int, double> a1;
   //直接查询值
   a1.first = 2;
   auto v1 = a1.second;

   //tie解包
   int v1;
   double v2
   tie(v1, v2) = a1;
   tie(v1, std::ignore) = a1;//不解包std::ignore
   //Structured Binding解包
   auto[va1, va2] = a1;

   // Using the constructor to declare and initialize a pair
   pair <int, double> p1 ( 10, 1.1e-2 );

   // Compare using the helper function to declare and initialize a pair
   pair <int, double> p2;
   p2 = make_pair ( 10, 2.22e-1 );

   // Making a copy of a pair
   pair <int, double> p3 ( p1 );

   auto p4 = p3;

   // 交换
   p4.swap(a1);

   auto p5 = make_pair<int, double> ( 15, 25.5 );

   //与std::map
   map <int, int> m1;
   m1.insert ( pair <int, int> ( 1, 10 ) );
   m1.insert ( pair <int, int> ( 2, 20 ) );
}

std::tuple

Microsoft C++ <tuple>

初始化

#include <tuple>
using namespace std;
typedef tuple <int, double, string> ids;

int main()
{
     // 无参构造
     ids t1;

     // Using the constructor to declare and initialize a tuple
     ids p1(10, 1.1e-2, "one");

     // Compare using the helper function to declare and initialize a tuple
     ids p2;
     p2 = make_tuple(10, 2.22e-1, "two");

     // Making a copy of a tuple
     ids p3(p1);

     auto t2 = make_tuple<int, double, string>(0, 1.1, "123");

     // tie 初始化
     int a1 = 0;
     float a2 = 0.1f;
     int a3 = 0;
     auto t3 = tie(a1, a2, a3);

     // forward_as_tuple 初始化
     auto t4 = forward_as_tuple(a1, a2, a3);
}

获取值

//get
void print_ids(const ids& i)
{
   cout << "( "
        << get<0>(i) << ", "
        << get<1>(i) << ", "
        << get<2>(i) << " )." << endl;
}

//tie解包
auto t1 = make_tuple<int, double, string>(0, 1.1, "123");
int vt1;
double vt2;
string vt3;
tie(vt1, std::ignore, vt3) = t1;

//Structured Binding解包
auto [vt11, vt21, vt31] = t1;

获取tuple的数量

auto t1 = make_tuple<int, double, string>(0, 1.1, "123");
size_t tNum = tuple_size<decltype(t1)>::value;

拼接

std::tuple<int, int, int> t5 = {1, 2, 3};
std::tuple<int, int, int> t6 = {1, 2, 3};
std::tuple<int, int, int, int, int, int> t7 = tuple_cat(t5, t6);

apply(C++17)

将一个tuple直接解构,用于函数的参数,从而完成函数的调用,std::pair同样适用

int getAdd(int a1, int a2, int a3)
{
    return a1 + a2 + a3;
}

std::tuple<int, int, int> addArg {1, 2, 3};
std::cout << std::apply(getAdd, addArg) << std::endl;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值