cppintermediate10 minutes
Build a Function to Merge and Sort Two Arrays
Write a C++ function that takes two integer arrays as inputs, merges them into a single array, removes duplicates, and returns the sorted result.
Challenge prompt
Create a function named mergeAndSort that accepts two vectors of integers. The function should merge both vectors into one, eliminate any duplicate values, and return a new vector sorted in ascending order.
Guidance
- • Use STL containers like std::vector and algorithms to manage the arrays efficiently.
- • Think about how to remove duplicates after merging before sorting the array.
Hints
- • Consider using std::set or sorting the merged vector then removing duplicates with std::unique.
- • Remember that std::sort and std::unique require including the <algorithm> header.
Starter code
#include <vector>
std::vector<int> mergeAndSort(const std::vector<int>& arr1, const std::vector<int>& arr2) {
// Your implementation here
return {};
}Expected output
[1, 2, 3, 4, 5, 6, 7]
Core concepts
vectorssortingduplicates removal
Challenge a Friend
Send this duel to someone else and see if they can solve it.