-1

I need to copy from end to start an array of longs to an array of longs as is shown in the code bellow. Is there any function similar to memcpy for the required purpose ?

typedef long int myT;
const size_t n=5;
myT a[n];
myT b[n]={12,45,56,76,78};

int main(int argc, char **argv)
{
    myT *p1=&a[0];
    myT *p2=&b[n];
    for(auto i=n;i-->0;) 
        *p1++=*--p2;
    return 0;
}
George Kourtis
  • 2,381
  • 3
  • 18
  • 28
  • 2
    Possible duplicate of [C memcpy in reverse](http://stackoverflow.com/questions/2242498/c-memcpy-in-reverse) – Shark Mar 14 '16 at 11:04
  • 4
    [`std::reverse_copy(b, b+n, a)`](http://en.cppreference.com/w/cpp/algorithm/reverse_copy), or since C++11 `std::reverse_copy(std::begin(b), std::end(b), std::begin(a))` – Jonathan Wakely Mar 14 '16 at 11:06

1 Answers1

2

That's what std::reverse_copy does.

int main()
{
  std::reverse_copy(b, b+n, a);
}

or since C++11:

int main()
{
  std::reverse_copy(std::begin(b), std::end(b), std::begin(a));
}
Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
  • The implementation of reverse_copy is just as the code I shown. The question is if exists an efficient implementation that is optimized !!! – George Kourtis Mar 14 '16 at 11:21
  • Erm, that's not what you asked. You said "system function", which does not mean "efficient implementation that is optimized". Your code definitely doesn't do anything clever, using a standard library function _might be_ optimized to do something clever. So in general prefer the standard library function instead of rolling your own. For code like this you should trust the compiler to optimize it anyway. – Jonathan Wakely Mar 14 '16 at 11:41