I want to move the first 2 elements to given position in vector, the result is not right by using memmove
in following code:
vector<int> v{1, 2, 3, 4, 0};
memmove(&(v[3]), &(v[0]), 2);
The result by doing so is 1, 2, 3, 1, 0
, while the expectation is 1, 2, 3, 1, 2
. How can I achieve my job?
memmove
copies bytes, not arbitrary objects (like int
). So you would need to calculate the correct byte count with 2 * sizeof(int)
.
But a better way is to use std::copy_n
:
std::copy_n(v.begin(), 2, v.begin() + 3);