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.
A potential application requiring this would be reading a .csv file with unknown number of rows and columns. Right now, the only way I can think to do this without 开发者_如何学JAVAvariable number of variables is either a 2D vector, or coding in more columns than possibly can be in any input file the program receives
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:
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<vector<int>> data;
Use whatever suits you, and simplifies your problem!
Use either
std:vector<int> n
or
int* n = new int[x];
精彩评论