简体   繁体   English

C ++中的多维可变大小数组

[英]Multidimensional variable size array in C++

hi I want to do something like this: 嗨,我想做这样的事情:

int op(string s1, string s2){
    int x = s1.size();
    int y = s2.size();
    int matrix = new int[x][y]
    /* do stuff with matrix */
}

For some reason I get the following errors: 由于某种原因,我得到以下错误:

SuperString.cpp(69) : error C2540: non-constant expression as array bound
SuperString.cpp(69) : error C2440: 'initializing' : cannot convert from 'int (*)[1]' to 'int'
        This conversion requires a reinterpret_cast, a C-style cast or function-style cast
SuperString.cpp(71) : error C2109: subscript requires array or pointer type

Thanks! 谢谢!

Here is a summary of how to build a 2d array in C++ using various techniques. 这是如何使用各种技术在C ++中构建2d数组的摘要。

Static 2D Matrix: 静态2D矩阵:

const size_t N = 25; // the dimension of the matrix

int matrix[N][N]; // N must be known at compile-time.
// you can't change the size of N afterwards

for(size_t i = 0; i < N; ++i)
{
    for(size_t j = 0; j < N; ++j)
    {
        matrix[i][j] = /* random value! */;
    }
}

Dynamic 2d Matrix: 动态二维矩阵:

const size_t N = 25; // the dimension of the matrix
int** matrix = new int*[N]; // each element is a pointer to an array.

for(size_t i = 0; i < N; ++i)
    matrix[i] = new int[N]; // build rows

for(size_t i = 0; i < N; ++i)
{
    for(size_t j = 0; j < N; ++j)
    {
        matrix[i][j] = /* random value! */;
    }
}

// DON'T FORGET TO DELETE THE MATRIX!
for(size_t i = 0; i < N; ++i)
    delete matrix[i];

delete matrix;

Matrix using std::vector: 使用std :: vector的矩阵:

// Note: This has some additional overhead
// This overhead would be eliminated once C++0x becomes main-stream ;)
// I am talking about r-value references specifically.
typedef vector< vector<int> > Matrix;
typedef vector<int> Row;

const size_t N = 25; // the dimension of the matrix
Matrix matrix;

for(size_t i = 0; i < N; ++i)
{
    Row row(N);

    for(size_t j = 0; j < N; ++j)
    {
        row[j] = /* random value! */;
    }

    matrix.push_back(row); // push each row after you fill it
}

// Once you fill the matrix, you can use it like native arrays
for(size_t i = 0; i < N; ++i)
{
    for(size_t j = 0; j < N; ++j)
    {
        cout << matrix[i][j] << " ";
    }

    cout << endl;
}

3d matrix using boost::multi_array ( taken from boost multi_array docs ): 使用boost :: multi_array的3d矩阵( 取自boost multi_array文档 ):

// Note that this is much more efficient than using std::vector!
int 
main () {
  // Create a 3D array that is 3 x 4 x 2
  typedef boost::multi_array<double, 3> array_type;
  typedef array_type::index index;
  array_type A(boost::extents[3][4][2]);

  // Assign values to the elements
  int values = 0;
  for(index i = 0; i != 3; ++i) 
    for(index j = 0; j != 4; ++j)
      for(index k = 0; k != 2; ++k)
        A[i][j][k] = values++;

  // Verify values
  int verify = 0;
  for(index i = 0; i != 3; ++i) 
    for(index j = 0; j != 4; ++j)
      for(index k = 0; k != 2; ++k)
        assert(A[i][j][k] == verify++);

  return 0;
}

You need to declare the matrix var as int* matrix , as a dynamic array is declared as a pointer. 您需要将矩阵var声明为int* matrix ,因为动态数组被声明为指针。 But you can't do a 2d array in one new with both dimensions being variable. 但是您不能在两个维度都可变的情况下在一个新的二维数组中进行操作。 You can do a 1D array and do the indexing math on your own. 您可以自己制作一维数组并进行索引数学运算。
int* matrix = new int[x*y];
// Set element x1,y1 to 5
matrix[x1+y1*x] = 5;

Use boost::multi_array . 使用boost :: multi_array See the doc and this question for details. 有关详细信息,请参阅文档和此问题

That will help you avoid a lot of errors. 这将帮助您避免很多错误。

If the size of matrix does not need to change through the function, you can declare the int s storing the string length as const . 如果不需要通过函数更改matrix的大小,则可以将存储string长度的int声明为const This allows you to create a multi-dimensional array that can vary in size for each function call, but retains a constant size for the duration of the function. 这使您可以创建一个多维数组,该数组的大小可以随每个函数调用而变化,但在函数持续时间内保持不变的大小。

#include <iostream>
#include <string>

using namespace std;

int someFunc(string, string);

int someFunc(string s1, string s2)
{
    const int x = s1.length();
    const int y = s2.length();

    int matrix[x][y];
    int result=0;

    for(int i=0;i<x;i++)
        for(int j=0;j<y;j++)
            matrix[i][j]=i*j;

    for(int i=0;i<x;i++)
        for(int j=0;j<y;j++)
            result+=matrix[i][j];

    return result;
}

int main()
{
    string s1 = "fubar";
    string s2 = "somethingelse";

    cout<<someFunc(s1,s2)<<endl;
}

EDIT: On reading one of the other answers posted while I was writing mine, I suppose you should use const size_t instead of const int . 编辑:在阅读我写我的文章时发布的其他答案之一时,我想您应该使用const size_t而不是const int Sorry, my C++ is just a little rusty. 抱歉,我的C ++有点生锈。

You cannot have a matrix of non-constant row size. 您不能具有行数不恒定的矩阵。

You may choose to have an "array of pointers to arrays" structure which can be indexed as pp[a][b] just as a matrix. 您可以选择具有“数组指针数组”结构,该结构可以像矩阵一样被索引为pp [a] [b]。 You cannot allocate such a structure with a single new . 您不能使用单个new分配这样的结构。 You will have to build it manually within a buffer. 您将必须在缓冲区中手动构建它。

It's more like a syntax problem. 这更像是语法问题。

Last check in gcc 4.4, int matrix[x][y]; 最后检查gcc 4.4, int matrix[x][y]; seems to work as expected. 似乎按预期工作。 If your array don't need resizing in the middle of the function. 如果您的数组不需要在函数中间调整大小。 You may try this syntax and see if it works in your compiler. 您可以尝试使用此语法,看看它是否可以在编译器中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM