wrote in news:13************************@posting.google.com in
comp.lang.c++:
I have an old set of library,where I used malloc to allocate
multidimensional(2 and 3) arrays,using only one malloc call(using void
pointers).I get the size of the array in run time.Now that I am moving
to C++,I wish to know if it is possible to allocate a
multi-dimensional(say 2 and 3) with just one (and only one) call to
'new'operator.The idea behind this is to have contiguous memory
locations for array data.Thanks in advance,for all your help.
Yes, but always prefer using a standard container to calling
new [].
#include <iostream>
#include <ostream>
#include <iomanip>
#include <vector>
template < typename T >
struct vector2d
{
vector2d(std::size_t n = 0) : m_Order(n), data( n * n ) {}
void set_Order(std::size_t n) { data.resize(n * (m_Order = n)); }
T *operator[](std::size_t off)
{
return &(data[off * m_Order]);
}
T const *operator[](std::size_t off) const
{
return &(data[off * m_Order]);
}
private:
std::size_t m_Order;
std::vector< T > data;
};
int main()
{
using namespace std;
vector2d< int > a(10);
int i, j;
for (i = 0; i < 10; ++i)
{
for (j = 0; j < 10; ++j)
{
a[i][j] = (i + 1) * (j + 1);
}
}
for (i = 0; i < 10; ++i)
{
for (j = 0; j < 10; ++j)
{
cout << setw(4) << a[i][j];
}
cout << endl;
}
}
Rob.
--
http://www.victim-prime.dsl.pipex.com/