当前位置: 代码迷 >> 综合 >> C++ std::pair, std::tuple
  详细解决方案

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

热度:40   发布时间:2023-12-07 21:44:33.0

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