Hi Rinu,
C++ provides a standard set of containers for storage and algorithms for doing common tasks. These are part of the Standard Template Library (STL).
Vectors are similar to arrays but they provide more functionality and are less prone to errors. For example, you can query the size of a vector with the size() method. Arrays require one to manage and store that information separately. Vectors can also grow dynamically.
STL containers are accessed via iterators. This is an abstraction that allows one to access different types of containers using a common interface. Iterators model pointers for arrays.
Merging is a common task and the STL provides an algorithm (std::merge) for doing just that. std::merge takes two containers and merges elements in ascending order into a third container.
If you go back to the code I posted, line one just reserves space for the result. It's not necessary because the result vector will grow on its own. It's a small optimization.
Line two merges the two containers into a third. It uses forward iterators for A (which is sorted in ascending order) and reverse iterators for B (reading it in reverse order, because it is in descending order) and uses a back_inserter iterator adapter to append the result to C. The result is a merged result set in ascending order.
The last line reverses the order of C in place (using the STL algorithm std::reverse) to give a result in descending order.
http://www.cplusplus.com/reference/algorithm/merge/
http://www.cplusplus.com/reference/std/iterator/back_inserter/
http://www.cplusplus.com/reference/algorithm/reverse/
You can do this with arrays as well (again, iterators model pointers, so algorithms can work on arrays).
1 2 3 4
|
C_size = A_size + B_size;
// Allocate C[C_size]
std::merge(A, A + A_size, std::reverse_iterator(B + B_size - 1), std::reverse_iterator(B - 1), C);
std::reverse(C, C + C_size);
|
Edit: add code tags.