C++ Code Example: join two arrays

This is a C++ program that merges two arrays into a third one.

  • First, it declares two arrays firstArray and secondArray with 5 elements each.
  • Then, it calculates the lengths of the arrays using end and begin and stores them in l1 and l2 respectively.
  • Next, it declares a third array joinedArray with length equal to the sum of the lengths of the first two arrays.
  • Then it uses the std::copy function from the <algorithm> library to copy the elements from the first array firstArray to joinedArray. The first argument to std::copy is the start of the source range, the second argument is the end of the source range, and the third argument is the start of the destination range.
  • Similarly, it uses std::copy to copy the elements from the second array secondArray to joinedArray, starting from the index l1 in the destination range to preserve the elements from the first array.
  • Finally, it prints the elements of the joined array, separated by spaces.
#include &lt;iostream&gt;
using namespace std;

int main() {
    int firstArray[] = {1, 2, 3, 4, 5};
    int secondArray[] = {6, 7, 8, 9, 10};

    int l1 = end(firstArray) - begin(firstArray);
    int l2 = end(secondArray) - begin(secondArray);

    int joinedArray[l1 + l2];
    std::copy(firstArray, firstArray + l1, joinedArray);
    std::copy(secondArray, secondArray + l2, joinedArray + l1);

    for (int i = 0; i < l1 + l2; i++) {
        std::cout << joinedArray[i] << ' ';
    }

    return 0;
}
Output
1 2 3 4 5 6 7 8 9 10