简体   繁体   English

C++中向量的向量顺序

[英]Which order for vector of vector in C++

I am using a structure std::vector< std::vector<double> > to store 2D data in a C++ code of size NxM.我正在使用结构std::vector< std::vector<double> >将二维数据存储在大小为 NxM 的 C++ 代码中。 Is there any performance issue related to the order in which I store my data if N is very different than M?如果 N 与 M 非常不同,是否存在与我存储数据的顺序相关的性能问题?

For instance, let's say N = 3 and M = 100000, I suppose it is faster to build 3 vectors of size 100000 than 100000 vectors of size 3. But for instance, if I am using a lot of push_back to fill them (assuming I don't know the initial size), isn't the other method faster?例如,假设 N = 3 和 M = 100000,我想构建 3 个大小为 100000 的向量比构建 100000 个大小为 3 的向量更快。但是例如,如果我使用大量push_back来填充它们(假设我不知道初始大小),其他方法不是更快吗?

I suppose it is faster to build 3 vectors of size 100000 than 100000 vectors of size 3.我想构建 3 个大小为 100000 的向量比构建 100000 个大小为 3 的向量要快。

Almost certainly, yes (and considerably so)!几乎可以肯定,是的(而且相当多)!

... if I am using a lot of push_back to fill them (assuming I don't know the initial size). ...如果我使用大量 push_back 来填充它们(假设我不知道初始大小)。

If you at least know (or suspect) what the maximum size is likely to be, you could use the reserve(nMax) function before your loop with the push_back calls, then call shrink_to_fit(nAct) afterwards, to free unneeded memory.如果您至少知道(或怀疑)最大大小可能是多少,则可以在循环之前使用reserve(nMax) function 进行push_back调用,然后调用shrink_to_fit(nAct)以释放不需要的 memory。 Such an approach would reduce the overheads caused by (potentially many) re-allocation calls.这种方法将减少由(可能很多)重新分配调用引起的开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM