1.tuple
1.1添加数据:
std::make_tuple 创建 tuple
std::make_tuple(dv, 2 * MAX);
1.2访问数据:
std::tuple<int, double, std::string> myTuple(10, 3.14, "Hello");
int intValue = std::get<0>(myTuple);
double doubleValue = std::get<1>(myTuple);
std::string stringValue = std::get<2>(myTuple);
2.1、tuple的创建和初始化
(1)直接初始化:
#include <tuple>
#include <string>
int main() {
// 直接初始化一个tuple
std::tuple<int, double, std::string> myTuple(10, 3.14, "Hello");
return 0;
}
(2)使用std::make_tuple函数进行初始化:
#include <tuple>
#include <string>
int main() {
// 使用make_tuple函数创建一个tuple
auto myTuple = std::make_tuple(10, 3.14, "Hello");
return 0;
}
(3)使用std::tie进行结构化绑定的初始化:
#include <tuple>
#include <string>
int main() {
int a;
double b;
std::string c;
std::tie(a, b, c) = std::make_tuple(10, 3.14, "Hello");
return 0;
}
(4)使用std::forward_as_tuple进行创建和初始化:
#include <tuple>
#include <string>
int main() {
auto myTuple = std::forward_as_tuple(10, 3.14, "Hello");
return 0;
}
2.2、tuple的成员访问
(1)使用 std::get 函数按索引访问元素:
#include <iostream>
#include <tuple>
int main() {
std::tuple<int, double, std::string> myTuple(10, 3.14, "Hello");
int intValue = std::get<0>(myTuple);
double doubleValue = std::get<1>(myTuple);
std::string stringValue = std::get<2>(myTuple);
std::cout << "Int value: " << intValue << std::endl;
std::cout << "Double value: " << doubleValue << std::endl;
std::cout << "String value: " << stringValue << std::endl;
return 0;
}
(2)使用 std::tie 进行结构化绑定,将 tuple 成员绑定到指定的变量:
#include <iostream>
#include <tuple>
int main() {
int a;
double b;
std::string c;
std::tuple<int, double, std::string> myTuple(10, 3.14, "Hello");
std::tie(a, b, c) = myTuple;
std::cout << "Int value: " << a << std::endl;
std::cout << "Double value: " << b << std::endl;
std::cout << "String value: " << c << std::endl;
return 0;
}
(3)使用结构化绑定(C++17):
#include <iostream>
#include <tuple>
int main() {
std::tuple<int, double, std::string> myTuple(10, 3.14, "Hello");
auto [intValue, doubleValue, stringValue] = myTuple;
std::cout << "Int value: " << intValue << std::endl;
std::cout << "Double value: " << doubleValue << std::endl;
std::cout << "String value: " << stringValue << std::endl;
return 0;
}
注意,std::forward_as_tuple的初始化方式是无法使用结构化绑定访问元素的。
2.3、效果展示
示例:
#include <tuple>
#include <iostream>
# include <string>
int main(int n,char ** args)
{
// 直接初始化:
std::tuple<int, double, std::string> mtuple(1,2.0,"3a");
// 使用`std::make_tuple`函数进行初始化:
auto mtuple2 = std::make_tuple(11,22.0,