[英]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. 我已经看到了很多有关C ++中矩形2-D数组的讨论,但是关于我正在使用的东西的讨论却很少。 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.
据我所知,ctor正在创建NUM_ID个空向量,至少在最初,getLength有效。 However, AddInfo seems to have allocation problems.
但是,AddInfo似乎有分配问题。
So, first of all, is this the best way of handling the problem? 那么,首先,这是解决问题的最佳方法吗? If so, am I dealing with these dynamically allocated, ragged 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>
. 但是,如果行数固定并且可以访问C ++ 0x / TR1,则可以使用
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: 然而:
.reserve()
it, no reallocation will happen, so nothing to worry about. .reserve()
,则不会发生重新分配,因此无需担心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.