まず者は、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
はおっと、配列のように見え、それが配列であることを意味しdoes't。 "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
である私の第二の溶液は、複数のアレイのようなものを使用していますが、サイズ変更機能を持って、あなたがオーバーライドすべきことです操作[]をクリックすると、自動的にユーザーに表示されます。
#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
、それは非常に大きな配列でない限り、その後の最も簡単な方法は、単に「無駄な」スペースを心配しないことです。 –
ベクトルを使うことができれば、これは完璧です。 – chris