variable number of variables in C++

前端 未结 2 1355
庸人自扰
庸人自扰 2021-01-20 21:14

Is it possible to make variable number of variables? For instance, say I want to declare some unknown number of integers, is there a way to have the code automatically decl

2条回答
  •  [愿得一人]
    2021-01-20 22:06

    Yes. (better and possible!)

    int x[100]; //100 variables, not a "variable" number, but maybe useful for you!
    
    int *px = new int[n];// n variables, n is known at runtime;
    
    //best
    std::vector ints; //best, recommended!
    

    Read about std::vector here:

    http://www.cplusplus.com/reference/stl/vector/

    See also std::list and other STL containers!


    EDIT:

    For multidimensional, you can use this:

    //Approach one!
    int **pData = new int*[rows]; //newing row pointer
    for ( int i = 0 ; i < rows ; i++ )
         pData[i] = new int[cols]; //newing column pointers
    
    //don't forget to delete this after you're done!
    for ( int i = 0 ; i < rows ; i++ )
         delete [] pData[i]; //deleting column pointers
    delete [] pData; //deleting row pointer
    
    //Approach two
    vector> data;
    

    Use whatever suits you, and simplifies your problem!

提交回复
热议问题