Concatenate TArrayDs

Hi!

What is the most efficient way to concatenate several TArrayDs?

Thanks,

Sebastian

Do you expect to return a new TArrayD or want to modify one of the inputs?

Primarily I want to copy the contents of N TArrayDs into a new, large, TArrayD. But a corresponding ‘Adopt’ would also be nice.

There isn’t really much to speed up then (since you will need to copy all
data) and I think the simplest solution would be to dynamically create an
a large enough array, copy all the data in there and then adopt in the target
array. One can avoid allocating the buffer in the TArray since Adopt will
reset it anyway.

#include <algorithm>
#include <TArrayD.h>

TArray concat(const TArray& a1, const TArray& a2) {
  const int n1 = a1.GetSize();
  const int n2 = a2.GetSize();

  const int n = n1 + n2;
  double* s = new double[n];

  std::copy(a1.GetArray(), a1.GetArray() + n1, s);
  std::copy(a2.GetArray(), a2.GetArray() + n2, s + n1);

  // declare a zero-sided TArray to avoid a allocation
  TArrayD a;
  a.Adopt(n, s); // resizes a

  // don't free s after Adopt

  return a;
}

If your compiler doesn’t optimize the call to the copy constructor away in the
function return pass the target as a TArray& argument and adopt there.

Fixed exception safe version:

#include <algorithm>
#include <TArrayD.h>

TArray concat(const TArray& a1, const TArray& a2) {
  const int n1 = a1.GetSize();
  const int n2 = a2.GetSize();

  const int n = n1 + n2;
  double* s = new double[n];

  TArrayD a(n);
  double* ap = a.GetArray();

  std::copy(a1.GetArray(), a1.GetArray() + n1, ap);
  std::copy(a2.GetArray(), a2.GetArray() + n2, ap + n1);

  return a;
}

If the return triggers a copy construct pass a by reference and call a.Set(n)
inside the function.