|
How to merge two arrays?
Consider the following two arrays:
int a[3] = {2,3,5};
int b[3] = {4,6,8};
These two arrays has to be merged and stored in a third array c.
My expected result would be :
c[6] = {2,3,5,4,6,8};
How to do this?
|
|
|
|
|
OK, I had to delete my first answer, because it was a C# solution. Sorry. Now my brain is switsched in C-mode
You can use memcpy. But allways be aware of the size of the target array! It has to be large enough to take all of the elements.
int a[] = { 2, 4, 6};
int b[] = { 3, 5, 7};
int c[6];
memcpy(c, a, sizeof(a));
memcpy(c + 3, b, sizeof(b));
Hope it helps.
|
|
|
|
|
pix_programmer wrote: How to do this? Coding!
Another option would be using std::vector , and using the insert[^] method.
Veni, vidi, vici.
|
|
|
|
|
CPallini wrote: Coding! Now that's a brilliant idea; who'd a thunk it?
One of these days I'm going to think of a really clever signature.
|
|
|
|
|
I know I'm an innovator.
Veni, vidi, vici.
|
|
|
|
|
CPallini wrote: Another option would be using std::vector , and using the insert[^] method. I agree.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"Show me a community that obeys the Ten Commandments and I'll show you a less crowded prison system." - Anonymous
|
|
|
|
|
1. determine the required size of the resulting container
2. Allocate a container of that size on the heap.
3. copy the elements to the new container.
If you have trouble following those steps, you better learn basic C/C++ by reading a good book or tutorial. A good one can be found at http://www.cplusplus.com/doc/tutorial/[^]
|
|
|
|
|
This is a simple program. I think in my opinion programming skill will develop through thinking, practice etc.
here your problem is simple. so try to implement self such a problem. i will give the logic.
1. allocate required array size for destination array.
2.copy the content from source array to destination.
I also agree with Richard and pallini
|
|
|
|