简体   繁体   English

声明未知维的二维数组的最佳方法是什么?

[英]What's the best way to declare a bidimensional array of unknown dimensions?

I need to declare and store a bidimensional array of strings. 我需要声明和存储字符串的二维数组。 I have no way of knowing the size of both dimensions beforehand. 我无法事先知道两个尺寸的大小。 C++ requires me to know the size of at least the second array, correct? C ++要求我至少知道第二个数组的大小,对吗? If so, what's the best way to go about this? 如果是这样,最好的方法是什么?

Use std::vector . 使用std::vector In fact you should already be doing this even if you know the size, unless you have very good reasons not to. 实际上,即使您知道大小,也应该已经这样做,除非您有充分的理由不这样做。

As other answers stated, std::vector<> is the appropriate collection for the job. 如其他答案所述, std::vector<>是适合该作业的集合。

To declare a 2D vector of strings, use: 要声明字符串的二维向量,请使用:

std::vector<std::vector<std::string>> strings;

Once populated, you can use the familiar subscript notation to access elements: 填充后,您可以使用熟悉的下标符号来访问元素:

const std::string& at(strings[i][j]);

Don't use 'raw' arrays, since you don't know the size. 不要使用“原始”数组,因为您不知道大小。 One possibility would be to use the standard container std::vector . 一种可能性是使用标准容器std::vector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM