1

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?

vinllen
  • 1,369
  • 2
  • 18
  • 36

1 Answers1

4

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);
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • Yes, it's right. It looks like `memmove` using another temporary memory to store the source data which is inefficient – vinllen Jan 02 '17 at 11:33
  • 2
    @vinllen In practice, no. Check out the "notes" section here: http://en.cppreference.com/w/cpp/string/byte/memmove. – Emil Laine Jan 02 '17 at 11:37
  • I still have a question, this post(http://www.cplusplus.com/reference/algorithm/copy_n/) says "If the ranges overlap, some of the elements in the range pointed by result may have undefined but valid values." What's the meaning of "undefined but valid" ? The function template seems it not supports overlapped ranges – vinllen Jan 02 '17 at 11:58
  • @vinllen The standard doesn't specify the order in which elements are copied. Thus, the result of the operation is implementation-dependent for overlapping ranges. – Joseph Thomson Jan 02 '17 at 13:39