[英]Define 2d array with dynamic first dimension and static second in c++
I would like to define int array in which first dimension is choosen dynamically but second is static -- something like int array[][8]
.我想定义 int 数组,其中第一个维度是动态选择的,但第二个是 static - 类似于int array[][8]
。 Unfortunatelly I can not allocate such array dynamically.不幸的是我不能动态分配这样的数组。 int ary[][8] = new int[11][8];
Produces error:产生错误:
error: initializer fails to determine size of ‘array’
6 | int array[][8] = new int[11][8];
| ^~~~~~~~~~~~~~
2d.cpp:6:20: error: array must be initialized with a brace-enclosed initializer
or when I try following code:或者当我尝试以下代码时:
int array[][8] = new int*[11];
array[0] = new int[8];
I get我明白了
2d2.cpp:6:22: error: initializer fails to determine size of ‘array’
6 | int array[][8] = new int*[11];
| ^~~~~~~~~~~~
2d2.cpp:6:22: error: array must be initialized with a brace-enclosed initializer
2d2.cpp:7:25: error: incompatible types in assignment of ‘int*’ to ‘int [8]’
7 | array[0] = new int[8];
Is that even possible in c++?这在 c++ 中是否可行?
Just use std::vector
and std::array
:只需使用std::vector
和std::array
:
#include <vector>
#include <array>
#include <iostream>
int main()
{
using MyArray = std::vector<std::array<int, 8>>;
MyArray arr {11};
for (int i {0}; i < 8; ++i)
arr[i][i] = i;
for (const auto& v : arr) {
for (auto x : v) {
std::cout << x << " ";
}
std::cout << std::endl;
}
}
I will answer my own question:我将回答我自己的问题:
int (*array)[8] = new int[11][8];
I forgot how bad C++ rules for creating type definitions -- especially including pointers, arrays and function pointers -- are.我忘记了用于创建类型定义的 C++ 规则有多糟糕——尤其是包括指针、arrays 和 function 指针。 I added missing parentheses around array and now it is fine.我在数组周围添加了缺少的括号,现在很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.