Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

In C++20 the full program, retaining the same algorithm, can look like this:

    #include <algorithm>
    #include <iterator>
    #include <vector>
    #include <iostream>

    using namespace std::ranges;

    int main()
    {
        std::vector a = {1,2,3,4};
        std::vector b = {5,6,3,4};
        sort(a);
        sort(b);
        decltype(a) c;
        set_union (a, b, back_inserter(c));
        copy(c, std::ostream_iterator<int>(std::cout, "\n"));
    }
https://gcc.godbolt.org/z/44Ksf1hK8

Note the value type deduction when declaring the vectors, the use of back_inserter to avoid having to resize the result (c) vector, the use of std::ranges to do away with all the begin + end crapola, and the way ranges and iterators are inter-mixed.

C++ is always going to be a bit more verbose in trivial cases, but it's not that bad, and exposes a lot more flexibility in complex ones.



Thanks for the modernised version! It looks a lot better




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: