我是靠谱客的博主 舒心毛巾,最近开发中收集的这篇文章主要介绍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;

}







最后

以上就是舒心毛巾为你收集整理的C++ std::pair, std::tuple的全部内容,希望文章能够帮你解决C++ std::pair, std::tuple所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部