C++取决于输入的矩阵大小无法编译
有一个关于这个主题的主题正在处理数组,但我无法让它处理矩阵。
总之:
long rows, columns;
cin >> rows >> columns;
char *a = new char [rows];
在 Visual Studio 中编译得很好,但是:
char **a = new char[rows][columns];
或
char *a[] = new char[rows][columns];
或
char *a[] = new char[rows][columns]();
或
char **a = new char[rows][columns]();
根本不编译。
有什么帮助吗?谢谢
there is a topic about this subject which is working with arrays but I can't make it work with matrices.
(Topic: C++ array size dependent on function parameter causes compile errors)
In summary:
long rows, columns;
cin >> rows >> columns;
char *a = new char [rows];
compiles great in visual studio, but:
char **a = new char[rows][columns];
or
char *a[] = new char[rows][columns];
or
char *a[] = new char[rows][columns]();
or
char **a = new char[rows][columns]();
don't compile at all.
Any help? Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
array-new 运算符仅分配一维数组。有不同的解决方案,具体取决于您想要哪种数组结构。对于仅在运行时已知的维度,您可以创建一个数组数组:
或一个元素数组,其中包含指向每行第一个元素的关联指针数组(只需要对内存分配器进行两次命中):
任一者都可以让您通过
a[row][colum]
访问矩阵元素。另一种解决方案是仅使用一维数组并手动生成索引:
这可能比前两个解决方案中所需的双重间接更快。
您当然可以将其包装在一个类中以保留二维索引语法的外观:
The array-new operator only allocates 1-dimensional arrays. There are different solutions, depending on what sort of array structure you want. For dimensions only known at runtime, you can either create an array of arrays:
or an array of elements with an associated array of pointers to the first element of each row (requiring just two hits to the memory allocator):
Either one will let you access matrix elements via
a[row][column]
.An alternate solution is to just use the one-dimensional array and generate indexes by hand:
This is probably faster than the double-indirection required in the first two solutions.
You could of course wrap this in a class to preserve a semblance of 2D indexing syntax:
n 维数组不能像您尝试的那样直接分配。这是一种方法。
A n-dimensional array can not be directly allocated as you are trying to. Here is a way to do it.
如果你打算在 c++ 中使用 c 数组(而不是 std::vector),你就会被迫做这样的事情:
If you're going to use c-arrays in c++ (instead of std::vector), you're stuck doing something like this: