2种类型的多维数组cpp

时间:2015-09-23 12:39:07

标签: c++ multidimensional-array

这个问题是关于c ++的。如何创建一个数组,第一行有字符串,第二行有双打?我认为它应该是无效的,但它不起作用。还有其他方法吗?干杯

4 个答案:

答案 0 :(得分:5)

数组中不能有不同的类型。如果你需要有两种不同的类型,有几种方法可以做到这一点

  • 您可以使用std::pair之类的:std::pair<std::string, double>
  • 您可以使用structclass将不同类型包装在一起,如:

    struct some_name
    {
        std::string string_name;
        double double_name;
    };
    
  • 您可以使用std::mapstd::unordered_map

  • 您可以为std::sting部分使用2个单独的数组,为double部分使用1个
  • C ++ 11及更高版本的std::tuple也类似std::pair,但可以用于2种以上。

如果您在编译时知道数组的大小,我建议使用std::array,如果在运行时之前不知道数组大小,我建议使用std::vector

答案 1 :(得分:1)

您可以使用pair,但必须指定此数组的大小。例如:

std::array<std::pair<std::string, double>, 3> dummy{{"string", 1.1}, {"foo", 2.2}, {"bar", 3.3}};

然后,您可以使用firstsecond

访问元素
dummy[0].first  // it is a string (string)
dummy[1].second // it is a double (2.2)

您还可以创建struct并拥有struct ..

数组

答案 2 :(得分:0)

使用std::pair数组或您自己定义的结构/类。或者,如果您需要搜索,请考虑使用std::map

答案 3 :(得分:0)

您可以使用:

示例代码:使用Pair

vector <pair <string, double> > test;
test.push_back(make_pair("Age",15.6));
test.push_back(make_pair("Job",5));
cout << test[0].first<<" " << test[0].second;

使用结构:

struct str_test{
string name;
double value;
};
str_test temp;
temp.name = "Some";
temp.value = 1.1;
vector<str_test>test;
test.push_back(temp);
cout << test[0].name <<" "<<test[0].value;
相关问题