c++(5):std::tuple学习

        c++ tuple元组数据结构,可以将多个不同类型的数据打包在一起,可以用在很多地方,如列表(一行或一列)、元组(一组数据)、键值对(进行索引)

示例代码:

std_tuple_exemple.cpp

#include //c++元组数据结构对应的头文件
#include 
#include 
#include 
 
std::tuple get_student(int id)//定义函数,在main主函数之前,不需要函数声明
{
    if (id == 0) return std::make_tuple(3.8, 'A', "Lisa Simpson");//创建一个元组数据
    if (id == 1) return std::make_tuple(2.9, 'C', "Milhouse Van Houten");
    if (id == 2) return std::make_tuple(1.7, 'D', "Ralph Wiggum");
    throw std::invalid_argument("id");
}
  	
int main()
{
    auto student0 = get_student(0);
    //注意此处的std::get("变量名"),是获取第n个数据
    std::cout << "ID: 0, "
              << "GPA: " << std::get<0>(student0) << ", "
              << "grade: " << std::get<1>(student0) << ", "
              << "name: " << std::get<2>(student0) << '\n';
 
    double gpa1;
    char grade1;
    std::string name1;
    std::tie(gpa1, grade1, name1) = get_student(1);
    std::cout << "ID: 1, "
              << "GPA: " << gpa1 << ", "
              << "grade: " << grade1 << ", "
              << "name: " << name1 << '\n';
 
    // C++17 structured binding:
    auto [ gpa2, grade2, name2 ] = get_student(2);
    std::cout << "ID: 2, "
              << "GPA: " << gpa2 << ", "
              << "grade: " << grade2 << ", "
              << "name: " << name2 << '\n';
}

std::get 访问元组指定元素 

make_tuple 创建由参数类型定义的类型的元组对象

按字典顺序比较元组中的值

        operator==
operator!=
operator<
operator<=
operator>
operator>=
operator<=>

tuple_cat  通过连接任意数量的元组创建一个元组

forward_as_tuple  创建一个转发引用的元组

tie 创建一个左值引用的元组或将一个元组解包到单个对象中

编译运行:

#编译
g++ std_tuple_exemple.cpp -o std_tuple

运行:
./std_tuple

编译运行结果如下:

meng@meng:~/ideas/c++_ws/std_tuple$ g++ std_tuple_exemple.cpp -o std_tuple
std_tuple_exemple.cpp: In function ‘int main()’:
std_tuple_exemple.cpp:32:10: warning: decomposition declaration only available with -std=c++1z or -std=gnu++1z
     auto [ gpa2, grade2, name2 ] = get_student(2);
          ^
meng@meng:~/ideas/c++_ws/std_tuple$ ./std_tuple 
ID: 0, GPA: 3.8, grade: A, name: Lisa Simpson
ID: 1, GPA: 2.9, grade: C, name: Milhouse Van Houten
ID: 2, GPA: 1.7, grade: D, name: Ralph Wiggum

c++(5):std::tuple学习_第1张图片

官方链接:

std::tuple - cppreference.com

你可能感兴趣的:(c++,学习,c++,tuple,数据结构,元组)