Initialising 2D object

Hi,

I have been experimenting with a class creating 2D objects and defining functions using them. You could interpret it as a classic matrix class I suppose.

There's the method of using:
1
2
3
4
5
6
7
template <typename T>
T ** object2D;
object2D = new T*[rows];
for(int i=0;i<rows;i++)
{
   object2D[i] = new T[cols];
}


Tried that, it works. Currently I'm using a vector approach:
1
2
template <typename T>
vector<vector<T>> object2D;


In both cases, elements can be accessed through the simple object2D[i][j]. That way I can read the whole object and edit it elementwise.

I am however looking for a way to initialise the whole thing at once instead of having to do it element by element.

Something like this possibility if you define a new array: double x[2][2] = {{1,2},{3,4}};

I want to be able to do that with my own object, perhaps through operator overloading? Any suggestions would be most welcome. Also, I assume this is newbie enough for the beginners forum, but if it isn't please alert me and do not just leave me without an answer. Thanks in advance.

Last edited on
http://www.cplusplus.com/forum/articles/7459/

Initialising multi-variable arrays (esp as a vector) is very difficult. You have to remember, what if someone overrides your template with a class?
Note that a vector containing a vector must be declared without using two >'s next to each other. >> would be parsed as a single token.
Zaita, I understand that this definition is not foolproof, but that is not something I'm currently looking to change. It works for what I am using it for and that's for the moment fine by me. I had already read what you linked. Thanks though, it certainly is an interesting post.

I still don't know however, whether there is a method that would allow me to initialise multiple elements at once, with a function or an operator overload. Anyone?

And Seymore, I see how that could be a problem, but I didn't encounter any troubles. I'll remember it for if I ever do get an error relating to that.
FWIW, boost::array allows you to use array syntax to assign elements:

 
boost::array<6> array = { 1, 2, 3, 4, 5, 6 };


Newer compilers handle the >> ambiguity.
Topic archived. No new replies allowed.