I’m trying to create my own container for an array of any dimension for numerical computing. I would like to do this using templates so that I could overload the subscript operator [] so that it works like normal arrays and vectors e.g. access entries like a[10][10][10] etc.
I am having trouble getting the constructor to work when trying to create containers to hold multidimensional arrays. Please help!
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
using namespace std;
template <class T>
class container{
public:
inline T& operator[](int i){return data[i];}
container(int si, T initval){
size=si;
data=new T[size];
transform(data,data+size,data, [initval] (T d) {return initval;});
// transform fills array with the initial value.
}
~container(){delete [] data;}
private:
T* data;
int size;
};
int main(){
//For example:
vector<vector<int>> v1(10,vector<int>(10,0)); //2D 10x10
vector<vector<vector<int>>> v2(10,vector<vector<int>>(10,vector<int>(10,0)));
//3D 10x10x10
container<int> c1(10,0); //1D 10x1 works!
container<container<int>> c2(10,container<int>(10,0)); //2D 10x10 fails!
system("pause");
return 0;
}
VS10 error output:
error C2512: 'container<T>' : no appropriate default constructor available
with
[
T=int
]
c:\users\jack\documents\visual studio 2010\projects\ref\ref\ref.cpp(11) : while compiling class template member function 'container<T>::container(int,T)'
with
[
T=container<int>
]
c:\users\jack\documents\visual studio 2010\projects\ref\ref\ref.cpp(28) : see reference to class template instantiation 'container<T>' being compiled
with
[
T=container<int>
]
Build FAILED.
I know I could just use valarray or a boost library, but I would like to understand how to create my own. Efficiency is important. Thanks!
Your constructor uses the expression
new T[size]and this requiresTto be default constructible (ifTis a class type).You need to do something like: allocate raw memory (e.g. using
operator new) and constructTinstances “in place” using a placementnewexpression. Alternatively, you could just givecontainera default constructor.