Search code examples
c++arraysintconcatenation

C++ concatenate two int arrays into one larger array


Is there a way to take two int arrays in C++

int * arr1;
int * arr2;
//pretend that in the lines below, we fill these two arrays with different
//int values

and then combine them into one larger array that contains both arrays' values?


Solution

  • Use std::copy defined in the header <algorithm>. The args are a pointer to the first element of the input, a pointer to one past the last element of the input, and a pointer to the first element of the output. ( https://en.cppreference.com/w/cpp/algorithm/copy )

    int * result = new int[size1 + size2];
    std::copy(arr1, arr1 + size1, result);
    std::copy(arr2, arr2 + size2, result + size1);
    

    Just suggestion, vector will do better as a dynamic array rather than pointer