C++ - 多维数组

发布于 2024-09-27 12:09:15 字数 152 浏览 0 评论 0原文

处理多维数组时,是否可以为数组分配两个不同的变量类型...

例如,您有数组 int example[i][j] 是否可以为 ij 是两种完全不同的变量类型,例如 int 和 string?

When dealing with multidimensional arrays, is it possible to assign two different variable types to the array...

For example you have the array int example[i][j] is it possible for i and j to be two completely different variable types such as int and string?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

雅心素梦 2024-10-04 12:09:15

听起来像您正在寻找:

std::vector<std::map<std::string, int> > myData1;

或者也许:

std::map<int, std::map<std::string, int> > myData2;

第一个需要您在使用索引运算符之前将向量调整为适当的大小:

myData1.resize(100);
myData1[25]["hello"] = 7;

...而第二个将允许您直接(并且稀疏地)分配给任何元素:

myData2[25]["hello"] = 7;

Sounds like you're looking for:

std::vector<std::map<std::string, int> > myData1;

or perhaps:

std::map<int, std::map<std::string, int> > myData2;

The first would require you to resize the vector to an appropriate size before using the indexing operators:

myData1.resize(100);
myData1[25]["hello"] = 7;

...while the second would allow you to assign to any element directly (and sparsely):

myData2[25]["hello"] = 7;
谁把谁当真 2024-10-04 12:09:15

不,那是不可能的。您可能想考虑使用 STL 地图

No. That's not possible. You may want to look into using the STL map.

壹場煙雨 2024-10-04 12:09:15

不可以,C++ 只允许整数类型(例如:int、long、unsigned int、size_t、char)作为索引。

如果您想按字符串进行索引,可以尝试 std::map 但尝试将其扩展到二维会变得很复杂。

No, C++ only allows integer types (ex: int, long, unsigned int, size_t, char) as indexes.

If you want to index by a string, you could try std::map<std::string,mytype> but it gets complicated trying to extend that to two dimensions.

摘星┃星的人 2024-10-04 12:09:15

不,但您可以使用 std::maps

No, but you could use std::maps.

一曲琵琶半遮面シ 2024-10-04 12:09:15

不可以,您只能使用整数类型作为索引。

No, you can only use integer types as indices.

巴黎盛开的樱花 2024-10-04 12:09:15

不,你不能。不过,您可以使用 std::map 来实现这一点。

No you can't. You could achieve this with std::map though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文