To create a function equal to C# Array.Copy in C++

Asked

Viewed 156 times

8

I would like to create a function similar to Array.Copy from C# to C++.

This function has the prototype thus:

public static void Copy(
    Array sourceArray,
    int sourceIndex,
    Array destinationArray,
    int destinationIndex,
    int length
);

And I’d like to do a function that does the same function in C++.

I tried to do using a for, but I couldn’t make it work with the destinationIndex.

My code:

template <T> void Buffer <T> ::copy(T * src, int indexSrc, T * dst, int indexDst, int elements) {
    for (int srcAux = indexSrc, dstAux = indexDst, int aux = 0; aux != elements; srcAux++, dstAux++, aux++) {
        dst[indexDst] = src[srcAux];
    }
}
  • Post what you’ve already done.

  • My function was like this: template<T>&#xA;void Buffer<T>::copy(T *src, int indexSrc, T *dst, int indexDst, int elements){&#xA; for(int srcAux = indexSrc, dstAux = indexDst, int aux = 0;aux != elements;srcAux++, dstAux++, aux++){&#xA; dst[indexDst] = src[srcAux];&#xA; }&#xA;}

1 answer

7


C++ already has something ready that does this with std::copy():

std::copy(std::begin(src), std::end(src), std::begin(dest));

I put in the Github for future reference.

Trying to translate the code from one language to another without understanding the language doesn’t work. Each language has its own specificity and way of doing each operation.

Our tag has information on how to start learning C++.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.