二维数组值
我想声明一个二维数组并为其赋值,而不运行 for 循环。
我想我可以使用以下想法,
int array[5] = {1,2,3,4,5};
它也可以很好地初始化二维数组。但显然我的编译器不喜欢这样。
/*
1 8 12 20 25
5 9 13 24 26
*/
#include <iostream.h>
int main()
{
int arr[2][5] = {0}; // This actually initializes everything to 0.
arr [1] [] = {1,8,12,20,25}; // Line 11
arr [2] [] = {5,9,13,24,26};
return 0;
}
J:\CPP\Grid>bcc32.exe Grid.cpp
用于 Win32 的 Borland C++ 5.5.1 版权所有 (c) 1993, 2000 Borland
网格.cpp:
错误 E2188 Grid.cpp 11:函数 main() 中的表达式语法
错误 E2188 Grid.cpp 12:函数 main() 中的表达式语法
警告 W8004 Grid.cpp 14:“arr”被分配了一个从未在 funct 中使用的值 离子主()
* 编译中有 2 个错误 *
请帮助了解使用我的值集初始化 2d 数组的正确方法。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
像这样:
这应该包含在你的 C++ 教科书中:你使用的是哪一本?
不管怎样,最好考虑使用 std::vector 或一些现成的矩阵类,例如来自 Boost 的矩阵类。
Like this:
This should be covered by your C++ textbook: which one are you using?
Anyway, better, consider using
std::vector
or some ready-made matrix class e.g. from Boost.在 C 或 C++ 中初始化多维数组的正确方法是
如果需要,您可以使用相同的技巧来初始化更高维的数组。
另外,在初始代码中要小心 - 您试图在数组中使用 1 索引偏移量来初始化它。这没有编译,但如果编译了,就会导致问题,因为 C 数组是 0 索引的!
The proper way to initialize a multidimensional array in C or C++ is
You can use this same trick to initialize even higher-dimensional arrays if you want.
Also, be careful in your initial code - you were trying to use 1-indexed offsets into the array to initialize it. This didn't compile, but if it did it would cause problems because C arrays are 0-indexed!
只是想指出您不需要指定数组的所有维度。
最左边的维度可以由编译器“猜测”。
Just want to point out you do not need to specify all dimensions of the array.
The leftmost dimension can be 'guessed' by the compiler.
int iArray[2][2] = {{1, 2}, {3, 4}};
将二维数组视为数组的数组。
int iArray[2][2] = {{1, 2}, {3, 4}};
Think of a 2D array as an array of arrays.
一种替代方法是将二维数组表示为一维数组。这可以使逐元素操作更加高效。您可能应该将其包装在一个也包含宽度和高度的类中。
另一种替代方法是将 2D 数组表示为
std::vector 。 >
。这将允许您使用 STL 的算法进行数组运算,并且向量还将为您处理内存管理。One alternative is to represent your 2D array as a 1D array. This can make element-wise operations more efficient. You should probably wrap it in a class that would also contain width and height.
Another alternative is to represent a 2D array as an
std::vector<std::vector<int> >
. This will let you use STL's algorithms for array arithmetic, and the vector will also take care of memory management for you.