简体   繁体   English

C ++:向量中向量列表的有效副本

[英]C++ : efficient copy of a list of vectors in a vector

I am looking for the most efficient way to copy the content of a list of vectors in a vector. 我正在寻找在向量中复制向量列表内容的最有效方法。 I want to avoid as far as possible memory reallocation. 我想尽可能避免重新分配内存。

My problem is the following : I have : 我的问题如下:我有:

  • a std::vector<int> v containing N elements 包含N个元素的std::vector<int> v

  • a list of vector std::vector< std::vector<int>* > vlist 向量std::vector< std::vector<int>* > vlist

  • and I know that the total number of elements M in the vectors of vlist is <= N (N and M can be very large) 而且我知道vlist向量中元素M的总数为<= N(N和M可以非常大)

I want to copy all the elements of vlist in v (first all the elements of vlist[0], then all the elements of vlist[1] etc...) and at the end reduce the v size to M (my project don't use C++2011). 我想复制v中的vlist的所有元素(首先复制vlist [0]的所有元素,然后复制vlist [1]的所有元素,等等...),最后将v的大小减小到M(我的项目don (不使用C ++ 2011)。

How to do that as efficiently as possible ? 如何尽可能有效地做到这一点?

Thank you very much. 非常感谢你。

EDIT : remark : v is already filled with N elements and I want to replace them with M (<= N) elements coming from the other vectors. 编辑:备注:v已被N个元素填充,我想用来自其他向量的M个(<= N)元素替换它们。

I have no idea if this is the most efficient way , but this is a way : 我不知道这是否是最有效的方法 ,但这是一种方法

std::vector<int> v;
std::vector< std::vector<int>* > vlist;
int j = 0;
for(int i = 0; i < vlist.size(); ++i) {
  std::copy(vlist[i]->begin(), vlist[i]->end(), &v[j]);
  j += vlist[i]->size();
}
v.resize(j);

If you really want the most efficient way, you might have to implement several different ways and compare their speeds. 如果您确实想要最有效的方法,则可能必须实现几种不同的方法并比较它们的速度。

The most efficient way is to not copy it. 最有效的方法是不复制它。 What is your application doing that requires it? 您的应用程序需要做什么? Also, why do you have a vector<* vector<int> > instead of just vector<vector<int> > ? 另外,为什么要有vector<* vector<int> >而不是vector<vector<int> > Design around it, use pimpl, lazy copy, etc. 围绕它进行设计,使用pimpl,惰性复制等。

And in the end I'm not sure what you think you can do that's going to beat std's default copy constructor. 最后,我不确定您认为您能做些什么,这会击败std的默认副本构造函数。 Have you profiled your application to determine the default ctor is a bottleneck? 您是否已对应用程序进行了概要分析,以确定默认的ctor是瓶颈?

std::vector<int> v;
v.reserve(N);
for(size_t i = 0; i<vlist.size(); i++)
{
   v.insert(v.end(), vlist[i]->begin(), vlist[i]->end());
}

This should be efficient enough if M is close to N. Otherwise it's better to compute M before allocating the memory, and use v.reserve(M). 如果M接近N,这应该足够有效。否则,最好在分配内存之前计算M,然后使用v.reserve(M)。

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

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