C++ Online Compiler
Example: Merge Two Sorted Arrays (STL std::merge) in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Merge Two Sorted Arrays (STL std::merge) #include <iostream> #include <vector> #include <algorithm> // Required for std::merge int main() { // Step 1: Define the two sorted input vectors std::vector<int> arr1 = {1, 3, 5, 7, 9}; std::vector<int> arr2 = {2, 4, 6, 8, 10, 12}; // Step 2: Create a destination vector with enough capacity // It should be large enough to hold all elements from both source vectors std::vector<int> merged_arr(arr1.size() + arr2.size()); // Step 3: Use std::merge to combine the elements // Parameters: // - arr1.begin(), arr1.end(): Input range 1 // - arr2.begin(), arr2.end(): Input range 2 // - merged_arr.begin(): Output iterator where the merged elements will be stored std::merge(arr1.begin(), arr1.end(), arr2.begin(), arr2.end(), merged_arr.begin()); // Step 4: Print the merged array std::cout << "Merged array using std::merge: "; for (int val : merged_arr) { std::cout << val << " "; } std::cout << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS