如何创建用C给定尺寸的二维阵列++ [英] How to create a two dimensional array of given size in C++

查看:107
本文介绍了如何创建用C给定尺寸的二维阵列++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个给定大小的正方形矩阵。我知道如何创建一个给定大小的动态一维阵列。没有两个dimensinal阵列相同的工作像下面的线?

  CIN>>大小;
为int * a [] [] =新INT [大小] [SIZE]


解决方案

 为int * a [] [] =新INT [大小] [SIZE]


不,这是行不通的。

 的main.cpp:4:错误:只有一个分配的数组的第一个维度可能有动态大小
    新的INT [大小] [SIZE]
                  ^ ~~~

如果该行的大小是固定的,那么你可以这样做:

  //分配与`size`行和10列的数组
INT(*数组)[10] =新的INT [大小] [10];

在C ++中,你不能有两个维度,其中两个维度是动态的原料数组。这是因为原始数组索引中三分球方面的工作;例如,为了一个指针访问第二行到第一需要由行的大小递增。但是,当行的大小是动态数组不知道大小等C ++不知道如何找出如何做指针递增。

如果你想与多个动态维数组,那么你需要或者结构数组分配,使得C ++的默认数组索引逻辑可以处理它(如顶答案的这个中重复的问题),或者你需要实现找出适当的逻辑指针递增自己。

有关的阵列,其中每行具有相同的大小,我建议不要使用多个分配诸如这些答案提示,或使用矢量的矢量。采用向量的向量地址做手工分配的难度和危险性,但它仍然使用更多的内存,并且不允许更快的内存访问模式。

有一个不同的方法,扁平化多维数组,可以为code作为易于读取和写入任何其他的办法,不使用额外的内存,并可以执行好得多。

一个平面数组是指你只使用具有相同数量的元素所需的二维数组的一个二维数组,你多维指标和相应的单维度指标​​之间的转换执行算术。随着它看起来像:

 为int * ARR =新的INT [ROW_COUNT * COLUMN_COUNT]。

I ,列Ĵ中的二维数组对应于改编[COLUMN_COUNT * I + J] 改编[N] 在行对应的元素 N / COLUMN_COUNT 和列 N%COLUMN_COUNT 。例如,在10列,0行0列对应于数组ARR [0] ; 0行1列correponds到改编[1] ;行1列0 correponds到改编[10] ;第1行,第1列对应于改编[11]


您应该避免做使用手动内存管理原删除,如<的情况下code>为int * ARR =新INT [大小]; 。相反,资源管理应该在 RAII 类里面包裹起来。用于管理动态分配的内存RAII类的一个例子是的std ::矢量

 的std ::矢量&lt;&INT GT; ARR(ROW_COUNT * COLUMN_COUNT);
ARR [COLUMN_COUNT * I​​ + J]

您还可以包住逻辑另一类起来计算指数:

 的#include&LT;矢量&GT;类Array2d {
  的std ::矢量&lt;&INT GT; ARR;
  诠释列;
上市:
  Array2d(INT行,诠释列)
  :ARR(行*列)
  ,列(列)
  {}  结构Array2dindex {INT行; INT列; };  INT和放大器;运营商[](Array2dindex我){
    返回ARR [*列+ i.row i.column];
  }
};#包括LT&;&iostream的GT;诠释主(){
  INT大小;
  给std :: cin&GT;&GT;尺寸;  Array2d ARR(尺寸,大小);  的for(int i = 0; I&LT;大小; ++ I){
    对于(INT J = 0; J&LT;大小; ++ j)条{
      改编[{I,J}] = 100;
    }
  }  的for(int i = 0; I&LT;大小; ++ I){
    对于(INT J = 0; J&LT;大小; ++ j)条{
      性病::法院LT&;&LT;改编[{I,J}]&LT;&LT; '';
    }
    性病::法院LT&;&LT;的'\\ n';
  }
}


I need to create a square matrix of a given size. I know how to create a dynamic one-dimensional array of a given size. Doesn't the same work for two dimensinal arrays like the lines below?

cin>>size;
int* a[][]=new int[size][size]

解决方案

int* a[][]=new int[size][size]

No, this doesn't work.

main.cpp:4: error: only the first dimension of an allocated array may have dynamic size
    new int[size][size];
                  ^~~~

If the size of the rows were fixed then you could do:

// allocate an array with `size` rows and 10 columns
int (*array)[10] = new int[size][10];

In C++ you can't have raw arrays with two dimensions where both dimensions are dynamic. This is because raw array indexing works in terms of pointers; for example, in order to access the second row a pointer to the first needs to be incremented by the size of the row. But when the size of a row is dynamic the array doesn't know that size and so C++ doesn't know how to figure out how to do the pointer increment.

If you want an array with multiple dynamic dimensions, then you need to either structure the array allocations such that C++'s default array indexing logic can handle it (such as the top answers to this duplicate question), or you need to implement the logic for figuring out the appropriate pointer increments yourself.

For an array where each row has the same size I would recommend against using multiple allocations such as those answers suggest, or using a vector of vectors. Using a vector of vectors addresses the difficulty and dangerousness of doing the allocations by hand, but it still uses more memory than necessary and doesn't allow faster memory access patterns.

A different approach, flattening the multi-dimensional array, can make for code as easy to read and write as any other approach, doesn't use extra memory, and can perform much, much better.

A flattened array means you use just a single dimentional array that has the same number of elements as your desired 2D array, and you perform arithmetic for converting between the multi-dimensional indices and the corresponding single dimensional index. With new it looks like:

int *arr = new int[row_count * column_count];

Row i, column j in the 2d array corresponds to arr[column_count*i + j]. arr[n] corresponds to the element at row n/column_count and column n% column_count. For example, in an array with 10 columns, row 0 column 0 corresponds to arr[0]; row 0, column 1 correponds to arr[1]; row 1 column 0 correponds to arr[10]; row 1, column 1 corresponds to arr[11].


You should avoid doing manual memory management using raw new and delete, such as in the case of int *arr = new int[size];. Instead resource management should be wrapped up inside a RAII class. One example of a RAII class for managing dynamically allocated memory is std::vector.

std::vector<int> arr(row_count * column_count);
arr[column_count*i + j]

You can further wrap the logic for computing indices up in another class:

#include <vector>

class Array2d {
  std::vector<int> arr;
  int columns;
public:
  Array2d(int rows, int columns)
  : arr(rows * columns)
  , columns(columns)
  {}

  struct Array2dindex { int row; int column; };

  int &operator[] (Array2dindex i) {
    return arr[columns*i.row + i.column];
  }
};

#include <iostream>

int main() {
  int size;
  std::cin >> size;

  Array2d arr(size, size);

  for (int i = 0; i < size; ++i) {
    for (int j = 0; j < size; ++j) {
      arr[{i, j}] = 100;
    }
  }

  for (int i = 0; i < size; ++i) {
    for (int j = 0; j < size; ++j) {
      std::cout << arr[{i, j}] << ' ';
    }
    std::cout << '\n';
  }
}


这篇关于如何创建用C给定尺寸的二维阵列++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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