Vincent
Vincent

Reputation: 60371

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 :

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).

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.

Upvotes: 1

Views: 1331

Answers (3)

Peter Popov
Peter Popov

Reputation: 662

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).

Upvotes: 0

Robᵩ
Robᵩ

Reputation: 168626

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.

Upvotes: 1

djechlin
djechlin

Reputation: 60768

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> > ? Design around it, use pimpl, lazy copy, etc.

And in the end I'm not sure what you think you can do that's going to beat std's default copy constructor. Have you profiled your application to determine the default ctor is a bottleneck?

Upvotes: 0

Related Questions