我是c ++的新手,我花了一个晚上想着这个。我想创建一个二维数组,给出第一维的长度。第二维的长度从1增加。对于2d数组a [] [],a [0] []有1个元素,a [1] []有2个元素,a [2] []有3个元素等。
它听起来不像是一个坚硬的结构,但我找不到两个来创建它 - 我所能做的就是创建ax * x数组,这意味着我浪费了一半的空间。
任何人都有任何想法?提前谢谢。
答案 0 :(得分:1)
尝试考虑数组的动态分配。
制作多维数组的另一种方法是使用已知的概念 作为指针的指针。就像罗恩周四所说的那样,大多数人都在想 像一个带有行和列的电子表格的二维数组(只是 很好),但“引擎盖下”,C ++正在使用ptr到ptrs。首先你 从创建基指针开始。接下来,分配一个行数组 指针并将第一个地址分配给基指针。 接下来,分配内存来保存每行列数据并分配 行指针数组中的地址
但如果你是CPP的新手,我认为你不会处理大量数据,所以不要担心内存!
答案 1 :(得分:1)
std::vector
解决方案:
vector< vector<int> > stairs;
for(int i = 0; i < n; i++) // n is size of your array
stairs[i].resize(i+1);
您也可以使用普通指针执行此操作:
int * stairs[n];
for(int i = 0; i < n ; i++)
stairs[i] = new int[i+1];
但是这次你不得不担心在不再需要时删除这个结构。
答案 2 :(得分:1)
一种解决方案是定义一个类,该类包含大小为x *(x + 1)/ 2的单维数据数组,并且重载type & operator()(int r, int c)
以执行正确类型的索引。
template<class datatype, int size>
class strange2dArray {
datatype data[size*(size+1)/2];
datatype & operator()(int r, int c) {
// assert if the indexes are correct
return data[r*(r+1)/2+c];
}
};
顺便说一句,除非你是为了学习C ++而做的,否则你应该使用某种数学库(或其他)来为你提供这样的基本数据结构。他们将更加有效和安全地实施它。
答案 3 :(得分:0)
首先让我们看看Python的测试:
>>> a=[]
>>> a[0]=3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> a={}
>>> a[0]=3
糟糕,看起来像数组,并不代表它是数组。如果想要“array”的动态大小,可以使用映射。 是的,这是第一个解决方案:
#include <map>
#include <iostream>
using namespace std;
typedef std::map<int, int> array_d2; //length of second dimensional is increased
array_d2 myArray[10] ; //length of first dimensional is given
int main()
{
myArray[0][1] = 3;
myArray[0][2] = 311;
//following are tests
cout << myArray[0][1] << endl;
cout << myArray[0][2] << endl;
return 0;
}
(输出为:)
$ ./test
3
311
我的第二个解决方案是使用更像数组的东西,但是具有resize功能,你应该覆盖opertation []以自动为用户使用。
#include <vector>
#include <iostream>
using namespace std;
//length of second dimensional is increased
class array_d2 {
int m_size;
vector<int> m_vector;
public:
array_d2 (int size=10) {
m_size = size;
m_vector.resize(m_size);
};
int& operator[] ( int index ) {
if (index >= m_size) {
m_size = index + 1;
m_vector.resize(m_size);
}
return m_vector[index];
};
};
array_d2 myArray[10] ; //length of first dimensional is given
int main()
{
myArray[0][1] = 3;
myArray[0][20] = 311;
myArray[1][11] = 4;
myArray[1][12] = 411;
//following are tests
cout << myArray[0][1] << endl;
cout << myArray[0][20] << endl;
cout << myArray[1][11] << endl;
cout << myArray[1][12] << endl;
return 0;
}
(输出)
$ ./test1
3
311
4
411