zoukankan      html  css  js  c++  java
  • 二维数组的动态分配

    一维数组分配比较简单,在此略过。但是平时经常遇到需要动态分配二维数组的情况。下面给出几种二维数组分配方式。

    注:二维数组行坐标、列坐标都是通过m,n来传递的。

    1. 利用一维数组分配方式,模拟二维数组

    其实栈上二维数组仍然是个连续的内存空间,只不过在访问时做了相应的处理。那么,动态分配时,也可分配一块连续的内存空间。访问时通过(d + i m + j )访问即可。

    1. int m = 6, n = 3;
    2. char *d = (char * )malloc( sizeof( int )* m * n );
    3. for( int i = 0; i<m; ++i ){
    4. for ( int j = 0; j<n; ++j )
    5. {
    6. *(d + i*m + n ) = i + j;
    7. cout << static_cast<int>( *(d + i*m + n ) ) << " ";
    8. }
    9. cout << endl;
    10. }

    2. 利用STL vector实现动态二维数组

    STL中vector是基于固定长度数组的延伸,那么利用这种方法也可以得到动态二维数组。具体方法见代码。

    1. int m = 6, n = 3;
    2. vector< vector<int> > d( m, vector<int>( n, 0 ));
    3. for( int i = 0; i<m; ++i ){
    4. for ( int j = 0; j<n; ++j )
    5. {
    6. d[i][j] = i + j;
    7. cout << static_cast<int>( d[i][j] ) << " ";
    8. }
    9. cout << endl;
    10. }

    3. 层层递进分配法

    此方法参考了:http://blog.csdn.net/walle_love_eva/article/details/8934397
    直接复制代码:

    1. char** allocateCharacterBoard(size_t xDimension, size_t yDimension)
    2. {
    3. char** myArray = new char*[xDimension]; // Allocate first dimension
    4. for (size_t i = 0; i < xDimension; i++)
    5. {
    6. myArray[i] = new char[yDimension]; // Allocate ith subarray
    7. }
    8. return myArray;
    9. }
    10. void releaseCharacterBoard(char** myArray, size_t xDimension)
    11. {
    12. for (size_t i = 0; i < xDimension; i++)
    13. {
    14. delete [] myArray[i]; // Delete ith subarray
    15. }
    16. delete [] myArray; // Delete first dimension
    17. }

    上面总结的三种方法是我现在觉得比较好的方法,如果你有更好的方法,欢迎留言讨论。

  • 相关阅读:
    使用PHP类库PHPqrCode生成二维码
    40+个对初学者非常有用的PHP技巧
    (高级篇)jQuery学习之jQuery Ajax用法详解
    lerna管理前端模块实践
    Node.js:深入浅出 http 与 stream
    从koa-session源码解读session本质
    Elastichsearch实践
    Linux代理搭建TinyProxy
    linux常用命令
    node前后端同构的踩坑经历
  • 原文地址:https://www.cnblogs.com/miraclecoder/p/4051173.html
Copyright © 2011-2022 走看看