具有可变大小行的 C++ 2 维数组 [英] C++ 2 dimensional array with variable size rows

查看:21
本文介绍了具有可变大小行的 C++ 2 维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个 2D 数组,例如 arr[][] 有 5 行且每行包含可变数量的列?

How can you create a 2D array,say, arr[][] with 5 rows and each row has a variable number of columns in it?

可能 arr[5][]第一行 arr[0][] 4 列

possibly arr[5][] with 1st row arr[0][] with 4 columns

第二行 arr[1][] 有 5 列等等?

2nd row arr[1][] with 5 columns and so on?

我不介意 STL 向量解决方案,但我还不太了解向量.

I wouldn't mind a STL vector solution but I don't know vectors very well yet.

推荐答案

使用 C++11,您可以使用向量轻松完成(添加换行符以提高可读性):

With C++11, you can do it easily with vectors (line breakes added for readability):

std::vector< std::vector <int > > arr = {
{1,2,3},
{4,5},
{6,7,8,9,0}
};

如果您没有 C++11 编译器,它的工作方式完全相同,但您将无法轻松初始化它们.您可以单独设置元素:

If you don't have a C++11 compiler, it works the exact same way, but you will not be able to initialize them as easy. You can set elements individually:

std::vector< std::vector <int > > arr;//vector of vectors. Think of each element as of a "row"
std::vector<int> sub;//a temporary "row"
sub.push_back(1);
sub.push_back(2);
arr.push_back(sub);//Adding a "row" to the vector
sub.clear();//Making another one
sub.push_back(1);
sub.push_back(12);
sub.push_back(54);
arr.push_back(sub);//Adding another "row" to the vector

或者你可以用一个普通数组初始化每个行":

Or you can initialize each "row" with an ordinary array:

std::vector< std::vector <int > > arr;
static const int arr[] = {1,2,3,4};//A "row" as an ordinary array
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) ); //Setting a "Row" as a vector
arr.push_back(vec);//Adding the "row" to the vector of vectors. 

用普通数组做你想做的事情是不可能的,因为当你制作一个 array[X][Y] 时,它自动是一个 X*Y矩阵.但是,您可以使用指针数组:

It's not exactly possible to do what you want with ordinary arrays, since when you make an array[X][Y], it automaticaly is an X*Y matrix. You could, however, use an array of pointers:

int * array[3];
//also possible: int ** array =  new int*[3]; but don't forget to delete it afterwards.
int sub1[3] = {1,2,3};
int sub2[2] = {1,2};
int sub3[4] = {1,2,3,4};
array[0] = sub1;
array[1] = sub2;
array[2] = sub3;

并使用 array[X][Y] 访问元素.但是,矢量解决方案总体上要好得多.

and access elements with array[X][Y]. However, the vector solution is much better overall.

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

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