如何使用数组文件声明动态数组和2D数组 [英] How Do I Declare A Dynamic Array And 2D Array Using Array File

查看:89
本文介绍了如何使用数组文件声明动态数组和2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨^ _ ^

我们可以输入

Hi ^_^
we can type

array <int , 10> s = {0};



声明一维数组,现在我该如何声明一个二维数组用这种方式?另一方面,
如何使用这种方式声明动态数组(我的意思是让用户在运行程序后输入数组长度的方法是什么(1D和2D数组)) ?





非常感谢提前。


to declaration a 1D array, now how do I can declare a 2D array using this way ?
on the other hand how do i can declare a dynamic array using this way (I mean what is the way to let user type the length of the array after running the program (1D and 2D array)) ?


many thanks in advance.

推荐答案

这个问题不是非常清楚(顺便提一下我的问题评论),但您需要了解的是: http:// www.cplusplus.com/doc/tutorial/arrays [ ^ 。特别要注意多维数组部分。



此外,使用带有元数据的数组数据启动文本文件非常有用特别描述了阵列的尺寸。这样,代码可以在读取任何数组数据之前正确初始化数组。如果不以这种方式设计文件结构将导致需要两次读取相同的文件,这当然没什么好处。



-SA
The question is not really clear (see my comment to the question, by the way), but all you need to understand is this: http://www.cplusplus.com/doc/tutorial/arrays[^]. In particular, pay attention for the section "Multidimensional arrays".

Also, it's really useful to start your text file with array data with some metadata which, in particular, describes the dimensions of the array(s). This way, the code can initialize the arrays properly before reading any array data. Failure to design the file structure this way will lead to the need to read the same file twice, which of course would be nothing good.

—SA


多维 std :: array 的初始化确实有点令人惊讶:你需要添加一个额外的级别大括号例如
The initialization of a multidimensional std::array is indeed a bit a surprise: you need to add an extra level of braces. E.g.
#include <array>
...
using namespace std;
...
enum { OUTER = 3, INNER = 2 };

array<array<int, INNER>, OUTER> a =  { {{ 1, 2 }, { 3, 4 }, { 5, 6 }} } ;

for(size_t outer = 0; outer < OUTER; ++outer) {
	for(size_t inner = 0; inner < INNER; ++inner) {
		cout << "a[" << outer << "][" << inner << "] = " << a[outer][inner] << endl;
	}
}

结果:

a[0][0] = 1
a[0][1] = 2
a[1][0] = 3
a[1][1] = 4
a[2][0] = 5
a[2][1] = 6

除了外括号之外,您可以将所有元素保留为平面元素序列。



参见 http://stackoverflow.com/questions/17759757/multidimensional-stdarray [ ^ ]和引用的 C ++ 14提案 [ ^ ]修复缺陷。



For动态数组你可以使用嵌套 std :: vector s。

问候

Andi

You may leave away all but the outer braces and initialize the array as flat sequence of elements.

See also http://stackoverflow.com/questions/17759757/multidimensional-stdarray[^] and the referenced C++14 proposal[^] to fix that "defect".

For dynamic "arrays" you may use nested std::vectors.
Regards
Andi


这篇关于如何使用数组文件声明动态数组和2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆