Dynamical, non-rectangular two dimensional vectors in C++
I've seen a lot of discussions about rectangular 2-D arrays in C++, but not so much about what I'm working with. I need to keep identical information on a fixed number of things, so I've created a structure and I think I want to have a vector of vectors of them, so I've made the following definitions:
typedef struct sInfo {
int Length;
int RemainingReadLength;
int RemainingWriteLength;
bool FillFlag;
int Offset;
};
class InfoClass {
protected:
<vector<vector<sInfo> > vvInfo;
uint32 Index1;
uint32 Index2;
sInfo Info;
public:
InfoClass () : vvInfo(NUM_INFO) {}
void AddInfo() {
vvInfo[Index1].push_back(Info);
}
uint getLength () {
return (vvInfo[Index1][Index2].Length;
}
}
What I'm intending here is a fixed number of rows, each of which can expand or contract independently. As far as I can tell, the ctor is creating NUM_ID empty vectors, and at least at first, getLength works. However, AddInfo seems to have allocation problems.
So, first of all, is this the best way of handling the problem? If so, am I dealing with these dynamically allocated, ragged开发者_StackOverflow社区 vectors correctly?
Thanks
Your approach doesn't look too bad to me. However, if you have a fixed number of rows and have access to C++0x / TR1, you can use std::(tr1::)array<T,N>
.
Then, what are the allocation problems that you talk of?
Well, when you push in the outer vector it might reallocate and this causes all the inner vectors to be copied, which means they allocate new memory, copy the content and release the old memory.
However:
- C++0x no longer has this problem, because it uses move constructors when reallocating and (provided the standard library author correctly implemented those move constructors) they keep using the old memory for the new object.
- The allocation strategy is designed so that each member is copied only few times on average (1-2 for reallocation factor 2, 3-4 for reallocation factor 1.5; depends on particular implementation).
- Implementation using copy-on-write won't have this problem, but IIRC no standard library uses it for vectors (while some do for strings)
- If you know the size of outer vector in advance and
.reserve()
it, no reallocation will happen, so nothing to worry about.
精彩评论