如何使用字符串AND浮点数创建2D数组?

时间:2018-04-20 05:28:24

标签: c++ arrays multidimensional-array data-structures

我的infile.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)数组

2 个答案:

答案 0 :(得分:0)

如果你没有像你在评论中所说的那样使用std::map,你可以用struct做这样的事情:

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;
}

答案 1 :(得分:0)

在Hamed的答案中使用像这样的结构是可能的。

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

使用C-array实际上并不是非常C-plus-plussy。但是如果你的老师喜欢顽皮的东西你真的可以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存储在另一个维度中。