Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ concatenate two int arrays into one larger array

Tags:

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?

like image 500
kjh Avatar asked Oct 09 '12 00:10

kjh


People also ask

Can we concatenate two arrays in C?

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.

How do I get the size of an array in C++?

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]);


2 Answers

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

like image 70
SwiftMango Avatar answered Oct 14 '22 21:10

SwiftMango


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()); 
like image 32
Reed Copsey Avatar answered Oct 14 '22 22:10

Reed Copsey