std::tuple、std::tie(可用于结构体大小比较)、std::pair用法

本文介绍了C++中的tuple数据结构,重点讲解了tuple的使用方法,包括如何初始化、通过下标获取元素、std::tie进行元素解包以及std::ignore的运用。同时,与pair进行了对比,并展示了在结构体比较中的应用。

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

1、tuple应用:
解释:是一个元组,可包含无限多不同类型变量,pair的升级版,但没有pair得成员变量first、second

1.1、代码:

// tuple example
#include <iostream>     // std::cout
#include <tuple>        // std::tuple, std::get, std::tie, std::ignore

int main ()
{
  std::tuple<int,char> foo (10,'x'); // 构造tuple
  auto bar = std::make_tuple ("test", 3.1, 14, 'y');
  std::get<2>(bar) = 100;   //通过下标获取元素
  int myint; char mychar;
  std::tie (myint, mychar) = foo;  // unpack elements
  std::tie (std::ignore, std::ignore, myint, mychar) = bar;  // unpack (with ignore)
  mychar = std::get<3>(bar);
  std::get<0>(foo) = std::get<2>(bar); //通过下标获取元素
  std::get<1>(foo) = mychar;
  std::cout << "foo contains: ";
  std::cout << std::get<0>(foo) << ' ';
  std::cout << std::get<1>(foo) << '\n';

  return 0;
}

用法:初始化tuple实例后,通过std::tie解包元素,利用std::ignore忽略指定元素,通过std::get获取指针位置元素

参考资料:
1、 tuple、tie与ignore学习链接
2、C++ tuple元组的基本用法(总结)

2、std::tie用法:
解释:可以用于解包tuple元素;其构造函数返回一个元组
代码:

1、std::tie(a,b,c) = std::tuple<int,int,double>(1,2,4.1); // 用于解包tuple      
2、std::tuple<int, int, double>  pu = std::tie(a,b,c); // 创建到其参数或 std::ignore 实例的左值引用的tuple。        
3、std::tie(a, b) = std::make_tuple(2, 3);  

解释:
代码行1:tie用以解包元组,获取元组中元素值
代码行2:tie构造返回的是一个元组
用法:用于结构体大小比较:

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); 
}
}; 

参考资料:
解包tuple:http://www.cplusplus.com/reference/tuple/tie/
tie用于struct比较:https://zh.cppreference.com/w/cpp/utility/tuple/tie

3、Pair:
代码:

// pair::pair example
#include <utility>      // std::pair, std::make_pair
#include <string>       // std::string
#include <iostream>     // std::cout

int main () {
  std::pair <std::string,double> product1;                     // default constructor
  std::pair <std::string,double> product2 ("tomatoes",2.30);   // value init
  std::pair <std::string,double> product3 (product2);          // copy constructor

  product1 = std::make_pair(std::string("lightbulbs"),0.99);   // using make_pair (move)

  product2.first = "shoes";                  // the type of first is string
  product2.second = 39.90;                   // the type of second is double

  std::cout << "The price of " << product1.first << " is $" << product1.second << '\n';
  std::cout << "The price of " << product2.first << " is $" << product2.second << '\n';
  std::cout << "The price of " << product3.first << " is $" << product3.second << '\n';
  return 0;
}

参考资料:std::pair::pair

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值