Understanding how merge() works?

Here’s the code.

#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;

bool comp (int a, int b) {
    return a > b;
}

int main()
{
    vector<int> v1 = { 4, 1, 2 };
    vector<int> v2 = { 3, 5, 1 };
    vector<int> v3(6);
    merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin(), comp);
    for(int i:v3) cout << i << " ";
}

The output comes out to be 4 3 5 1 2 1. Can anyone explain how this works?

See the “Possible Implementation” here: std::merge - cppreference.com

std::merge is designed to work with a pair of sorted inputs - though the page doesn’t explicitly mention it, you’re probably going to get strange results with unsorted ones :slight_smile:

2 Likes