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?
To concate two arrays, we need at least three array variables. We shall take two arrays and then based on some constraint, will copy their content into one single array. Here in this example, we shall take two arrays one will hold even values and another will hold odd values and we shall concate to get one array.
In C++, we use sizeof() operator to find the size of desired data type, variables, and constants. It is a compile-time execution operator. We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);
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
If you're using arrays, you need to allocate a new array large enough to store all of the values, then copy the values into the arrays. This would require knowing the array sizes, etc.
If you use std::vector
instead of arrays (which has other benefits), this becomes simpler:
std::vector<int> results; results.reserve(arr1.size() + arr2.size()); results.insert(results.end(), arr1.begin(), arr1.end()); results.insert(results.end(), arr2.begin(), arr2.end());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With