From what I know, declaring a dynamic array is:
int *array = new int[x];
My question is, how can I declare a dynamic 2D array?
For example:
int *array = new int[constant][dynamic];
And from what I found out is the number of rows can't be dynamic. Are there any ways to do it?
One easy technique that I use in these kind of situations is that I create a struct for storing the 1D array, and create an array of those 1D arrays.
struct BaseArray {
BaseArray() = default;
BaseArray(int count) : pArray(new int[count]) {}
~BaseArray() { delete[] pArray; }
int* pArray = nullptr;
};
int main()
{
BaseArray* pArray = new BaseArray[constant]{dynamic};
}
Now the other simple way is to use std::vector
. It'll look something like this,
std::vector<std::vector<int>> array(constant, std::vector<int>(dynamic));
I recommend using std::vector
as its more feature complete and takes a lot of burden off of your shoulder.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.