赞
踩
tuple:元组
https://zh.cppreference.com/w/cpp/utility/tuple
(C++11 起)
类模板 std::tuple
是固定大小的异类值汇集。它是 std::pair 的推广。
example:
- std::tuple<int, int> foo_tuple()
- {
- return {1, -1}; // N4387 前错误
- return std::tuple<int, int>{1, -1}; // 始终有效, tuple可以使用初始化列表进行赋值。
- return std::make_tuple(1, -1); // 始终有效
- }
example:
- #include <tuple>
- #include <iostream>
- #include <string>
- #include <stdexcept>
-
- std::tuple<double, char, std::string> get_student(int id)
- {
- if (id == 0) return std::make_tuple(3.8, 'A', "Lisa Simpson"); //生成一个std::tuple
- 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::cout << "ID: 0, "
- << "GPA: " << std::get<0>(student0) << ", " //std::get用于取出tuple中的某个值
- << "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::tie的用法!!std::tie会将变量的引用整合成一个tuple,从而实现批量赋值
- std::cout << "ID: 1, "
- << "GPA: " << gpa1 << ", "
- << "grade: " << grade1 << ", "
- << "name: " << name1 << '\n';
-
- // C++17 结构化绑定:
- auto [ gpa2, grade2, name2 ] = get_student(2);
- std::cout << "ID: 2, "
- << "GPA: " << gpa2 << ", "
- << "grade: " << grade2 << ", "
- << "name: " << name2 << '\n';
- }
还可以使用std::ignore忽略某些tuple中的某些返回值,如上例中的:
- double gpa1;
- std::string name1;
- std::tie(gpa1, ignore, name1) = get_student(1);
可
https://zh.cppreference.com/w/cpp/utility/tuple/get
以使用get<常量表达式>(tuple_name)
来访问或修改(从c++14开始返回的const类型引用,不能修改了吧)tuple的元素(返回引用)。
Example:
- #include <iostream>
- #include <string>
- #include <tuple>
-
- int main()
- {
- auto t = std::make_tuple(1, "Foo", 3.14);
- // 基于下标的访问
- std::cout << "(" << std::get<0>(t) << ", " << std::get<1>(t)
- << ", " << std::get<2>(t) << ")\n";
- // 基于类型的访问( C++14 起)
- std::cout << "(" << std::get<int>(t) << ", " << std::get<const char*>(t)
- << ", " << std::get<double>(t) << ")\n";
- // 注意: std::tie 和结构化绑定亦可用于分解 tuple
- }
我心无法.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。