Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clone vector?

Tags:

c++

networking

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

like image 516
user800799 Avatar asked Jun 22 '11 04:06

user800799


People also ask

What does it mean to clone into a vector?

Vector, cloning: A fragment of DNA into which another DNA fragment can be integrated. Cloning vectors are used to introduce foreign DNA into host cells, where that DNA can be reproduced (cloned) in large quantities.


2 Answers

You can easily copy a vector using its copy constructor:

vector<T> the_copy(the_original); // or
vector<T> the_copy = the_original;
like image 163
R. Martinho Fernandes Avatar answered Oct 05 '22 09:10

R. Martinho Fernandes


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

like image 42
mattn Avatar answered Oct 05 '22 11:10

mattn