如何创建带有字符串和浮点数的 2D 数组

How to create a 2D array with strings AND floats?

本文关键字:字符串 浮点数 数组 2D 何创建 创建      更新时间:2023-10-16

我的文件.txt看起来像这样:

Takoma_store 2.7 71.3 14.7 23.9 51.2
Bethesda_store 12.7 8.9 17.8 7.9 18.3
Baltimore_store 123.5 134.8 564.6 451.8 521.9 1796.6
District_store 56.2 26.5 123.4 456.7 789.3 1452.1
Prince_store 23.1 28.3 12.9 120.0 45.8 230.1
Columbia_store 21.5 123.0 80.9 99.0 91.20 415.60
Bowie_store 100.0 100.0 100.0 100.0 100.0 100.0

我需要创建一个看起来像这样的数组

[Takoma_store] [2.7, 71.3, 14.7, 23.9, 51.2]
[Bethesda_store] [12.7, 8.9, 17.8, 7.9, 18.3]
[Baltimore_store] [123.5, 134.8, 564.6, 451.8, 521.9, 1796.6]
[District_store] [56.2, 26.5, 123.4, 456.7, 789.3, 1452.1]
[Prince_store] [23.1, 28.3, 12.9, 120.0, 45.8, 230.1]
[Columbia_store] [21.5, 123.0, 80.9, 99.0, 91.20, 415.60]
[Bowie_store] [100.0, 100.0, 100.0, 100.0, 100.0, 100.0]

使用两个 for 循环。我知道它需要格式化如下:

for (int x = 0; x < number_of_stores; x++) {
    for (int y = 0; y < number_of_sales; y++) {
        //collect data from file
    }
}

但我不知道如何声明一个多维 (2D( 数组,该数组允许我收集字符串(商店名称(和浮点数(销售(

如果你不被允许使用std::map,正如你在评论中所说的那样,你可以用结构体做这样的事情:

struct strdbl
{
    std::string name;
    double nums[6];
};
int main()
{
    strdbl sf[10] = {
        {"Takoma_store", {2.7, 71.3, 14.7, 23.9, 51.2}},
        {"Bethesda_store", {12.7, 8.9, 17.8, 7.9, 18.3}},
        {"Baltimore_store", {123.5, 134.8, 564.6, 451.8, 521.9, 1796.6}},
        {"District_store", {56.2, 26.5, 123.4, 456.7, 789.3, 1452.1}},
        {"Prince_store", {23.1, 28.3, 12.9, 120.0, 45.8, 230.1}},
        {"Columbia_store", {21.5, 123.0, 80.9, 99.0, 91.20, 415.60}},
        {"Bowie_store", {100.0, 100.0, 100.0, 100.0, 100.0, 100.0}}
    };
    return 0;
}

使用像Hamed的答案那样的结构是一种可能性。

另一种方法是使用std::variant即 然后std::variant<std::string, std::array<double, 6>>制作一个数组。

使用 C 数组真的不是很 C 加加。但是如果你的老师喜欢顽皮的东西,你真的可以将std::string(或char*(double存储在同一个C数组中,如果你做一个void*数组,即:

char* store = "Takoma_store";
double d1   = 2.7;
double d2   = 71.3;
...
void* list[] = { &store, &d1, &d2 ...};

访问即 d1你会写double d = *(double*)list[1];.天呐!很讨厌!

我想不出C++还有什么比这更脏的了,你的老师可能会喜欢。您还可以将void*数组设为 2D 并将char*(或其他任何东西(存储在一个维度中,double存储在另一个维度中。