C ++多维数组 [英] C++ multi dimensional array

查看:56
本文介绍了C ++多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
C ++中的多维数组和指针?

在1D模式下,我可以声明一个数组,

Hi, In 1D I can declare an array like,

int *image = new int[W*H];

但是在二维中如何声明数组?

But in 2D how can I declare an array?

int *image = new int[W][H]; -- is it wrong??

推荐答案

int *image = new int[W][H]; -- is it wrong??

它不会编译.您应该先编译代码,才能知道问题的答案.

It will NOT compile. You should compile your code first, to know the answer of your question.

我认为您想这样做:

//memory allocation
int **image = new int*[W];
for(size_t i = 0 ; i < W ; i++ )
   image[i] = new int[H];

//use it as
 for(size_t i = 0 ; i < W ; i++ )
    for(size_t j = 0 ; j < H ; j++ )
          image[i][j] = some_value;
int value = image[20][30]; //get value at (20,30) assuming 20 < W and 30 < H

//memory deallocation
for(size_t i = 0 ; i < W ; i++ )
   delete [] image[i];
delete [] image;

但是,当您拥有 std :: vector 时,为什么还要做所有这些呢?您可以使用它来完成所有这些令人讨厌的事情.这是您应该如何使用 std :: vector :

But then why do all these when you've std::vector? You could use it which will do all these nasty thing itself. Here is how you should be using std::vector:

std::vector<std::vector<int> > image(W, std::vector<int>(H));
for(size_t i = 0 ; i < W ; i++ )
    for(size_t j = 0 ; j < H ; j++ )
          image[i][j] = some_value;
int value = image[20][30]; //get value at (20,30) assuming 20 < W and 30 < H

这篇关于C ++多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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