← Back to STL Containers
Question 572
Merge Two Sorted Vectors
Merge Two Sorted Vectors
Write a functionvector<int> mergeSorted(const vector<int>& a, const vector<int>& b)whereaandbare each sorted ascending. Return a new vector containing every element of both, sorted ascending. Requirements: 1. Keep one iterator intoaand one intob. 2. While both have elements left, compare the two current elements, push the smaller one into the result and advance only that iterator. When they are equal, take the one fromafirst. 3. When one input runs out, append everything remaining in the other (its leftover range). 4. Do not callsortorstd::merge; either input may be empty. The test prints the result's elements separated by spaces on one line. For {1, 3, 5} and {2, 4, 6} the line is1 2 3 4 5 6; for {1, 4, 9} and {2, 3} it is1 2 3 4 9. Do NOT write a main function.
Expected Output:
1 2 3 4 5 6 1 2 3 4 9
= newline. The output ends with a newline — print one after the last line.
Hints4 available
Sign in to use hintsTopics:
STL ContainersIterators
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)
Your Output
Run your code to see the output here...
Test Cases
Run your code to see test case results.