Variable number of variables in C ++

Is it possible to make a variable number of variables? For example, let's say I want to declare some unknown number of integers, is there a way to automatically declare the code

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

where x is a finite number of required variables.

A potential application requiring this will read a CSV file with an unknown number of rows and columns. Right now, the only way I can think of this without a variable number of variables is either a two-dimensional vector, or encoding in more columns than is possible in any input file that the program receives

+3
source share
2 answers

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::vectorhere:

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

. std::list STL!


EDIT:

, :

//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;

, , !

+7

std:vector<int> n

int* n = new int[x];
+5

Source: https://habr.com/ru/post/1790136/


All Articles