News for hackers. Stuff that matters.
Re:Porting Graphing Calculator from C++ to Swift by interpol_p on Sunday July 03, 2022 @03:13AM (#31965751)
I don't write C++ much anymore, but to take an example where we want to union two sets (I'm sure the C++ one could be better? I've adapted from multiple examples)

C++:

    int first[] = {1,2,3,4};
    int second[] = {5,6,3,4};
    std::vector<int> v(8);
    std::vector<int>::iterator it;

    std::sort (first,first + 4);     // 1 2 3 4
    std::sort (second,second + 4);   // 3 4 5 6

    it = std::set_union (first, first + 4, second, second + 4, v.begin());

    v.resize(it - v.begin());

    for(it = v.begin(); it != v.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

Swift:

    let a = Set([1,2,3,4])
    let b = Set([5,6,3,4])
    let c = a.union(b)
    print(c) //prints "[1, 2, 3, 5, 6, 4]"
Re:Porting Graphing Calculator from C++ to Swift by nly on Sunday July 03, 2022 @05:28AM (#31966373)
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.

Re:Porting Graphing Calculator from C++ to Swift by interpol_p on Sunday July 03, 2022 @10:54AM (#31968158)
Thanks for the modernised version! It looks a lot better
Re:Porting Graphing Calculator from C++ to Swift by gpderetta on Sunday July 03, 2022 @04:03AM (#31965979)

   std::set a{1,2,3};
   std::set b{5,6,3,4};
   std::set c{a};
   c.insert(b.begin, b.end());

   for(auto x: c)
      std::cout<<c<<' c;
   std::cout << '\n';