#include <vector>
template <typename T>
class TwoDVector{
public:
TwoDVector(){};
TwoDVector(int rows, int cols):m_data(rows, std::vector<T>(cols)){}
inline std::vector<T> & operator[](int i) { return m_data;}
inline const std::vector<T> & operator[] (int i) const { return m_data;}
void resize(int rows, int cols){
m_data.resize(rows);
for(int i = 0;i < rows;++i) m_data.resize(cols);
}
private:
std::vector<std::vector<T> > m_data;
};
Need help with wrapper for 2-d std::vector
Not sure if I am shooting at the wind hear but I am trying to make a simple wrapper for implementation of a 2-D std::vector I am having trouble getting my head around the constructor aspect of this. In order for it to generate the "2nd Demension" I would have to declare a variable like
TwoDVector<Square> Map(25,25);
correct?
And I could not simply use the default like so...
TwoDVector<Square> Map();
If I am correct in my assumption then I would not be able to declare an object of the type TwoDVector inside a .h file. Correct?
Any advice would be great
Regards
Chad
Quote:In order for it to generate the "2nd Demension" I would have to declare a variable likeCorrect...
TwoDVector<Square> Map(25,25);
correct?
Quote:And I could not simply use the default like so...Sure, you can use the default constructor [edit: but without the parentheses, as the_edd points out below); it will just create an empty array with dimensions 0,0. (By the way, you have an extra semicolon after your default constructor.)
TwoDVector<Square> Map();
Quote:If I am correct in my assumption then I would not be able to declare an object of the type TwoDVector inside a .h file.Why not?
I'm not sure if I understood your questions correctly though...
Also, you might take a look at the Boost.MultiArray library, if you haven't already.
[Edited by - jyk on January 28, 2008 6:07:12 PM]
IMHO a better way to do this would be to use a std::vector<T> and do the 2D-to-1D index mapping yourself (i=y*w+x). This allows people to take the address of index (0,0) and have a pointer to a contiguous block of memory as they would if they were using a 1D std::vector. If you do this though be wary of your resize() function. std::vector maintains its contents during a resize, so if a user of your class was to expect the same thing and they change the 2nd dimension they'll get a nasty surprise when the value at (5,6) is different before and after the resize.
Quote:Original post by chadsxe
And I could not simply use the default like so...
TwoDVector<Square> Map();
Careful, this declares a function called Map that takes no arguments and returns a TwoDVector<Square>. It is not an instantiation of TwoDVector<Square>. This may be why you're running in to trouble.
Drop the trailing ()
TwoDVector<Square> Map;
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement