Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
std::vector<std::vector<mytype> > my_2d_int_array(SizeX, std::vector<mytype>(SizeY));
Example code:
#include <iostream>
#include <vector>
int main(int argc, char* argv[])
{
int SizeX = 3;
int SizeY = 5;
std::vector<std::vector<int> > my_2d_int_array(SizeX, std::vector<int>(SizeY));
int x, y;
for(x = 0;x < my_2d_int_array.size();++x)
{
for(y = 0;y < my_2d_int_array[x].size();++y)
{
my_2d_int_array[x][y] = x*10 + y;
}
}
for(x = 0;x < my_2d_int_array.size();++x)
{
for(y = 0;y < my_2d_int_array[x].size();++y)
{
std::cout << my_2d_int_array[x][y] << std::endl;
}
}
return 0;
}
//The above method is simple, and requires no special class.
#include <vector>
template <typename T>
class dynamic_2d_array
{
public:
dynamic_2d_array(){};
dynamic_2d_array(int rows, int cols):m_data(rows, std::vector<T>(cols)){}
inline std::vector<T> & operator[](int i) { return m_data[i];}
inline const std::vector<T> & operator[] (int i) const { return m_data[i];}
void resize(int rows, int cols){
m_data.resize(rows);
for(int i = 0;i < rows;++i) m_data[i].resize(cols);
}
private:
std::vector<std::vector<T> > m_data;
};
void Func(int x, int y)
{
dynamic_2d_array <double> MyMatrix(x, y);
MyMatrix[0][0] = 1;
MyMatrix[0][1] = 2;
MyMatrix[1][0] = 33;
MyMatrix[1][1] = 44;
cout << MyMatrix[0][0] << MyMatrix[0][1] << MyMatrix[1][0] << MyMatrix[1][1] << endl;
}
template < typename T >
T **Allocate2DArray( int nRows, int nCols)
{
T **ppi;
T *pool;
T *curPtr;
//(step 1) allocate memory for array of elements of column
ppi = new T*[nRows];
//(step 2) allocate memory for array of elements of each row
pool = new T [nRows * nCols];
// Now point the pointers in the right place
curPtr = pool;
for( int i = 0; i < nRows; i++)
{
*(ppi + i) = curPtr;
curPtr += nCols;
}
return ppi;
}
template < typename T >
void Free2DArray(T** Array)
{
delete [] *Array;
delete [] Array;
}
int main()
{
double **d = Allocate2DArray<double>(10000, 10000);
d[0][0] = 10.0;
d[1][1] = 20.0;
d[9999][9999] = 2345.09;
Free2DArray(d);
}