'Inserting a new element to array

So my goal is to join two Arrays together and insert the new size of the new array in the beginning of the array.



Solution 1:[1]

Assuming you want to avoid manually writing code to copy array elements over "1 by 1", there are facilities in the language and standard libraries to do this for you.

This is the modern C++ way to do it:

short* ConcatArray(short* a1, short* a2)
{
    size_t len1 = a1[0];
    size_t len2 = a2[0];

    short* a3 = new short[len1 + len2 + 1]; // +1 for new length

    *a3 = (short)(len1 + len2 + 1);
    std::copy_n(a1, len1, a3+1);
    std::copy_n(a2, len2, a3 + 1 + len1);

    return a3;
}

Old "C" way (using new as allocator):

short* ConcatArray(short* a1, short* a2)
{
    size_t len1 = a1[0];
    size_t len2 = a2[0];

    short* a3 = new short[len1 + len2 + 1]; // +1 for new length

    *a3 = (short)(len1 + len2 + 1);
    memcpy(a3+1, a1, sizeof(*a1)*len1);
    memcpy(a3+1+len1, a2, sizeof(*a2)*len2);


    return a3;
}

Solution 2:[2]

You don't need to shift values if you copy them to the correct position in the first place. This should do what you want.

short int *ConcatArray(short int *a1, short int *a2)
{
    short int n = a1[0]; // size of array 1
    short int m = a2[0]; // size of array 2
    short int newSize = n + m + 1;

    short int *newArr = new short int[newSize];

    int i = 0; // current output position in newArr
    newArr[i++] = newSize;

    for (int j = 0; j < n; ++j, ++i) { // copy a1
        newArr[i] = a1[j];
    }

    for (int j = 0; j < m; ++j, ++i) { // copy a2
        newArr[i] = a2[j];
    }

    return newArr;
}

Here's the code working on Compiler Explorer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2