提问者:小点点

多维数组来存储三种不同的数据类型?


我有一组三个值对,我想存储在一个数组中,每个值具有不同的类型。

[string][int][double]用于存储诸如[John][12][40.025][Amy][20][16000.411]之类的内容,我希望能够按位置检索值。 我应该用什么容器?

我看过很多答案,但大多数都是关于两种数据类型的,我不知道哪一种更适合我的情况。


共2个答案

匿名用户

类的作用是这样的:

struct data {
    std::string name;
    int         name_describing_this_variable;
    double      another_descriptive_name;
};

可以将此类的实例存储在数组中:

data arr[] {
    {"John", 12, 40.025},
    {"Amy",  20, 16000.411},
};

匿名用户

使用在标题中声明的类模板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;
}

作为替代,您可以定义自己的复合类型(类或结构),它将包含所需类型的子对象。