C++可变大小数组的数组
我对 C++ 很陌生,我意识到以下内容不一定像我希望的那么简单,但我真的很感激更专业的意见。
我本质上是试图在可变大小数组的可变大小数组上实现动态迭代,类似于以下内容。
String *2d_array[][] = {{"A1","A2"},{"B1","B2","B3"},{"C1"}};
for (int i=0; i<2d_array.length; i++) {
for (int j=0; j<2d_array[i].length; j++) {
print(2d_array[i][j]);
}
}
有没有合理的方法来做到这一点?也许通过使用向量或其他结构?
谢谢 :)
I am very new to C++ and I realise the following is not necessarily as easy as I'd like it to be, but I'd really appreciate a more expert opinion.
I am essentially trying to achieve a dynamic iteration over a variable sized array of variable sized arrays similar to the following.
String *2d_array[][] = {{"A1","A2"},{"B1","B2","B3"},{"C1"}};
for (int i=0; i<2d_array.length; i++) {
for (int j=0; j<2d_array[i].length; j++) {
print(2d_array[i][j]);
}
}
Is there a reasonable way to do this? Perhaps by using a vector, or another struct?
Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在使用 C++ 字符串对象的纯 C 数组。 C 语言中没有可变大小的数组。除此之外,这段代码无论如何都不会编译,在这样的构造中,编译器将生成一个声明了最大长度的数组。在示例案例中,
如果您想要可变大小的数组,则必须使用 C++ STL(标准模板库)容器,例如向量或列表:
You are using a plain C array of C++ string objects. In C there are no variable sized arrays. Besides that this code wont compile anyway, in such a construct the compiler will generate a array of arrays that have the maximum length declared. In the sample case that would be
If you want variable sized arrays, you have to use C++ STL(Standard template library)-containers such as vector or list: