Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to append two arrays ( concatenate two arrays) C++

Tags:

c++

I am trying to find the fastest way to append two arrays together I know it is a simple problem. But I need a very quick way to do it maybe by using a library function

Here is my code below which does it without any library functions

  #include <iostream>
    #include <algorithm>

    using namespace std;

    int main()
    {
       int a[] = {1,2,3,4,5};
       int b[] = {6,7,8,9,10};
       int c[10];

       for(int i=0; i<5; i++)
       {
          c[i] = a[i];   
       }

       for(int i=5; i<10; i++)
       {
          c[i] = b[i-5];   
       }


       for(int i=0; i<10; i++)
       {
          cout << c[i] << endl;  
       }


}

what is a more efficient way ?

like image 891
Mozein Avatar asked Dec 06 '25 02:12

Mozein


1 Answers

First of all, I think your loops are fine. If you want to, you can try if merging them into one loop gives you any speed-up because you only need half the iterations:

for (int i = 0; i < 5; ++i) {
    c[i] = a[i];
    c[i+5] = b[i];
}

But measure this, it is by no means guaranteed to be faster. If the arrays always are that small, any difference in performance is highly unlikely.

If you want to use the <algorithm> library (which I like to do for readability, but in your case the loops are short enough), you can do it like this:

std::copy(a, a+5, c);
std::copy(b, b+5, c+5);

It most likely is not faster than the loops, but looks cleaner IMO. When the amount of data gets bigger, it might actually offer a speedup by being implemented in an optimized way, but as always, measure it.

I would stay away from memcpy though. It does not work on all types and offers no (or should not offer any) advantage over std::copy.

As a last remark, consider replacing the raw C-arrays with the modern std::array. One advantage here is that you can just copy it with =, plus some neat member functions like fill and size.

like image 157
Baum mit Augen Avatar answered Dec 10 '25 08:12

Baum mit Augen