Hi! I need to make dynamic multidimensional arrays using the vector class. I found in this page How to dynamically create a two dimensional array? - Microsoft: Visual C++ FAQ - Tek-Tips the way to do it in 2D, and now i'm trying to expand it to 3D but i don't understand how is the operator[] working, so i have problems. Here is my code:
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class Matrix {
protected:
std::vector<std::vector<T> > m_data;
public:
Matrix() {}
Matrix(int rows, int cols) : m_data(rows, std::vector<T>(cols)) {}
~Matrix() {}
inline void get_size(int& rows, int& cols) {
rows = m_data.size();
cols = m_data[0].size(); }
//operators
inline std::vector<T> & operator[](int i) { return m_data; }
inline const std::vector<T> & operator[] (int i) const { return m_data; }
};
template <typename T>
class MatrixTD {
protected:
Matrix<std::vector<T> > m_data;
public:
MatrixTD() {}
MatrixTD(int rows, int cols, int lays) : m_data(rows, cols) {
for(int i = 0; i < rows; ++i)
for(int j = 0; j < cols; ++j)
m_data[j].resize(lays); }
MatrixTD(int rows, int cols, int lays, T val) : m_data(rows, cols) {
for(int i = 0; i < rows; ++i){
for(int j = 0; j < cols; ++j){
m_data[j].resize(lays);
for(int k = 0; k < lays; ++k)
m_data[j][k] = val;
}
} }
~MatrixTD() {}
inline void get_size(int& rows, int& cols, int& lays) {
m_data.get_size(rows, cols);
lays = m_data[0][0].size(); }
//operators
inline std::vector<T> & operator[](int i) { return m_data; }
inline const std::vector<T> & operator[] (int i) const { return m_data; }
};
int main(){
int size = 5;
int s1, s2, s3;
MatrixTD<int> m3Dd(size, size, size, 0);
m3Dd.get_size(s1, s2, s3);
for(int i = 0; i < s1; ++i){
for(int j = 0; j < s2; ++j){
for(int k = 0; k < s3; ++k){
cout<<m3Dd[j][k]<<" ";
}
cout<<endl;
}
cout<<endl;
}
return 0;
}
And the compiler tels me:
vector3D.cpp: In member function �std::vector<T, std::allocator<_CharT> >& MatrixTD<T>::operator[](int) [with T = int]':
vector3D.cpp:113: instantiated from here
vector3D.cpp:47: error: invalid initialization of reference of type �std::vector<int, std::allocator<int> >&' from expression of type �std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >'
Note: I can access the data if I make m_data public and I use m_data[][][], but the operator[] doues not work in the 3D case.
Thank you in advance for any help!