user800799
user800799

Reputation: 3023

How do I clone vector?

I am using vector as an input buffer...

recv = read(m_fd, &m_vbuffer[totalRecv], SIZE_OF_BUFFER);

After it reads all data from the input buffer then it will put the data inside of the vector into the thread pool.

So I was trying to do clone the vector. I think I cannot just pass the pointer to the vector because of the new packets coming in and it overwrites the data inside of the vector.

However, I could not find a way to clone the vector. Please provide me a proper way to handle this. Also I will be very appreciated if you guys point out any problems using vectors as input buffer or tutorials related to this...

Upvotes: 10

Views: 35665

Answers (3)

Neil G
Neil G

Reputation: 33252

As Nemo points out, you might want to consider whether you really need a copy of the vector. Can you get away with transferring the contents using std::swap or std::move (if using C++0x)?

Upvotes: 0

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234634

You can easily copy a vector using its copy constructor:

vector<T> the_copy(the_original); // or
vector<T> the_copy = the_original;

Upvotes: 40

mattn
mattn

Reputation: 7733

At the first, you may have to call recv with &m_vbuffer[0]. About cloning of vector, use copy().

#include <algorithm>
...

vector<char> m_vcopy;
m_vcopy.reserve(m_vbuffer.size());
copy(m_vbuffer.begin(), m_vbuffer.end(), m_vcopy.begin());

However, note that the element should not be reference. :)

Upvotes: 2

Related Questions