C++ std::pair, std::tuple

std::pair 定义于<utility>

template <class T1, class T2> struct pair;
 
Pair of values
This class couples together a pair of values, which may be of different types ( T1 and  T2). The individual values can be accessed through its public members  first and  second.

std::tuple 定义于<tuple>

Tuple library
Tuples are objects that pack elements of -possibly- different types together in a single object, just like  pairobjects do for pairs of elements, but generalized for any number of elements.Conceptually, they are similar to plain old data structures (C-like structs) but instead of having named data members, its elements are accessed by their order in the  tuple.The selection of particular elements within a  tuple is done at the template-instantiation level, and thus, it must be specified at compile-time, with helper functions such as  get and  tie.The  tuple class is closely related to the  pair class (defined in header  <utility>): Tuples can be constructed from pairs, and pairs can be treated as tuples for certain purposes. array containers also have certain tuple-like functionalities.

#include <iostream>
#include <tuple>
#include <string>
#include <utility>
#include <stdexcept>

std::tuple<double, char, std::string> get_student(int id) {
  if (id == 0)
    return std::make_tuple(98.5, 'A', "qsa");
  if (id == 1)
    return std::make_tuple(77.0, 'B', "bb");

  throw std::invalid_argument("error !");
}

int main() {
  auto student = get_student(0);

  std::cout << "score " << std::get<0>(student)
    << " level " << std::get<1>(student)
    << " name " << std::get<2>(student) << std::endl;

  double score;
  char level;
  std::string name;
  std::tie(score, level, name) = get_student(1);
  std::cout << "score " << score << " level " << level << " name " << name << std::endl;

  std::pair<int, char> mypair(100, 'A');

  auto coll = std::tuple_cat(student, mypair);

  std::cout << std::get<0>(coll) << std::endl;
  std::cout << std::get<1>(coll) << std::endl;
  std::cout << std::get<2>(coll) << std::endl;
  std::cout << std::get<3>(coll) << std::endl;
  std::cout << std::get<4>(coll) << std::endl;

}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值