C++ 如何克隆载体?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6435032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I clone vector?
提问by user800799
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...
但是,我找不到克隆载体的方法。请为我提供处理此问题的正确方法。如果你们指出使用向量作为输入缓冲区或与此相关的教程的任何问题,我也将不胜感激...
回答by R. Martinho Fernandes
You can easily copy a vector using its copy constructor:
您可以使用其复制构造函数轻松复制向量:
vector<T> the_copy(the_original); // or
vector<T> the_copy = the_original;
回答by mattn
At the first, you may have to call recv with &m_vbuffer[0]
.
About cloning of vector, use copy().
首先,您可能需要使用&m_vbuffer[0]
. 关于载体的克隆,使用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. :)
但是,请注意该元素不应被引用。:)
回答by Neil G
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)?
正如 Nemo 指出的那样,您可能需要考虑是否真的需要向量的副本。您可以使用std::swap
or std::move
(如果使用 C++0x)传输内容吗?