如何创建带有字符串和浮点数的 2D 数组
How to create a 2D array with strings AND floats?
我的文件.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
存储在另一个维度中。
相关文章:
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何将时间字符串 (M:SS) 转换为浮点数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- C++ - 转换标准::浮点数组的字符串
- 如何对向量进行排序<浮点数,字符串>而不考虑字符串
- C++ 按数值对元组<字符串、浮点数>然后按字典顺序排序的向量
- 将浮点数转换为字符串时如何加快此代码的速度?
- 如何将带有浮点数的字符串转换为十进制?
- 将浮点数向量转换为十六进制/二进制字符串
- 精确且无公差地将浮点数转换为字符串
- 如何创建带有字符串和浮点数的 2D 数组
- 如何使用 c++ 模板实现整数、字符串、浮点数和日期对象的数组
- 解析文本文件中的字符串、整数和浮点数
- 假设浮点数或双 NaN 将始终作为字符串"nan"是否安全?
- 如何在不使用对象的情况下连接字符串、整数和浮点数
- 有没有一种简单的方法可以从嵌入的 GNU ARM C++字符串中解析浮点数?
- 将特定格式的字符串拆分为浮点数和字符串
- 有没有办法将数字作为字符串,并在不使用浮点数或双精度数的情况下将其四舍五入到确切的位数
- 在同一行中读取混合输入(字符串/浮点数),并将其存储在数组中
- 提升词法转换(负字符串---->浮点数)