简体   繁体   English

C ++中可变数量的变量

[英]variable number of variables in C++

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 declare 例如,假设我想声明一些未知数量的整数,是否有办法让代码自动声明

int n1;
int n2;
.
.
.
int nx;

where x is the final number of variables required. 其中x是所需变量的最终数量。

A potential application requiring this would be reading a .csv file with unknown number of rows and columns. 需要这个的潜在应用程序将读取具有未知行数和列数的.csv文件。 Right now, the only way I can think to do this without variable number of variables is either a 2D vector, or coding in more columns than possibly can be in any input file the program receives 现在,我认为在没有可变数量的变量的情况下做到这一点的唯一方法是2D向量,或者编码在更多列中,而不是可能在程序接收的任何输入文件中

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<int> ints; //best, recommended!

Read about std::vector here: 在这里阅读std::vector

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

See also std::list and other STL containers! 另请参见std::list和其他STL容器!


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<vector<int>> data;

Use whatever suits you, and simplifies your problem! 使用适合你的任何东西,简化你的问题!

Use either 使用其中之一

std:vector<int> n

or 要么

int* n = new int[x];

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

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