C ++中可变数量的变量 [英] variable number of variables in C++

查看:43
本文介绍了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;

其中x是所需变量的最终数量.

where x is the final number of variables required.

可能需要这样做的应用程序将读取具有未知行数和列数的.csv文件.现在,我认为没有可变数量的变量的唯一方法是2D向量,或者在程序可以接收的任何输入文件中编码的列数都多于

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

推荐答案

是.(更好,可能!)

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!

在此处了解有关 std :: vector 的信息

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

另请参见 std :: list 和其他STL容器!

See also std::list and other STL containers!

对于多维,可以使用以下方法:

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!

这篇关于C ++中可变数量的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆