C++ concatenate two int arrays into one larger array

101,163

Solution 1

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

Solution 2

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

Solution 3

Another alternative is to use expression templates and pretend the two are concatenated (lazy evaluation). Some links (you can do additional googling):

http://www10.informatik.uni-erlangen.de/~pflaum/pflaum/ProSeminar/ http://www.altdevblogaday.com/2012/01/23/abusing-c-with-expression-templates/ http://aszt.inf.elte.hu/~gsd/halado_cpp/ch06s06.html

If you are looking for ease of use, try:

#include <iostream>
#include <string>

int main()
{
  int arr1[] = {1, 2, 3};
  int arr2[] = {3, 4, 6};

  std::basic_string<int> s1(arr1, 3);
  std::basic_string<int> s2(arr2, 3);

  std::basic_string<int> concat(s1 + s2);

  for (std::basic_string<int>::const_iterator i(concat.begin());
    i != concat.end();
    ++i)
  {
    std::cout << *i << " ";
  }

  std::cout << std::endl;

  return 0;
}
Share:
101,163
kjh
Author by

kjh

Updated on December 18, 2020

Comments

  • kjh
    kjh over 3 years

    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?