我有一组三个值对,我想将它们存储在一个数组中,每个值都有不同的类型。
[string][int][double]
用于存储诸如[John][12][40.025]
[Amy][20][16000.411]
之类的东西,我希望能够按位置检索值。我应该使用什么容器?
我看过很多答案,但其中大多数是关于两种数据类型的,我不知道哪一种更适合我的情况。
这是类的用途:
struct data {
std::string name;
int name_describing_this_variable;
double another_descriptive_name;
};
您可以将此类的实例存储在数组中:
data arr[] {
{"John", 12, 40.025},
{"Amy", 20, 16000.411},
};
使用在标头<tuple>
中声明std::tuple
类模板。例如
#include <iostream>
#include <string>
#include <tuple>
int main()
{
std::tuple<std::string, int, double> t ={ "John", 12, 40.025 };
std::cout << std::get<0>( t ) << ", "
<< std::get<1>( t ) << ", "
<< std::get<2>( t ) << 'n';
std::cout << std::get<std::string>( t ) << ", "
<< std::get<int>( t ) << ", "
<< std::get<double>( t ) << 'n';
return 0;
}
程序输出为
John, 12, 40.025
John, 12, 40.025
您可以使用具有此类型的元素容器作为数组,因为元组中列出的类型是默认可构造的。
例如
#include <iostream>
#include <string>
#include <tuple>
int main()
{
std::tuple<std::string, int, double> t[1];
t[0] = { "John", 12, 40.025 };
std::cout << std::get<0>( t[0] ) << ", "
<< std::get<1>( t[0] ) << ", "
<< std::get<2>( t[0] ) << 'n';
std::cout << std::get<std::string>( t[0] ) << ", "
<< std::get<int>( t[0] ) << ", "
<< std::get<double>( t[0] ) << 'n';
return 0;
}
作为替代方法,您可以定义自己的复合类型(类或结构(,该类型将包含所需类型的子对象。