Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

c++ std::sort

#include <algorithm>
#include <functional>
#include <array>
#include <iostream>
#include <string_view>
 
int main()
{
    std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
 
    auto print = [&s](std::string_view const rem) {
        for (auto a : s) {
            std::cout << a << ' ';
        }
        std::cout << ": " << rem << '
';
    };
 
    std::sort(s.begin(), s.end());
    print("sorted with the default operator<");
 
    std::sort(s.begin(), s.end(), std::greater<int>());
    print("sorted with the standard library compare function object");
 
    struct {
        bool operator()(int a, int b) const { return a < b; }
    } customLess;
    std::sort(s.begin(), s.end(), customLess);
    print("sorted with a custom function object");
 
    std::sort(s.begin(), s.end(), [](int a, int b) {
        return a > b;
    });
    print("sorted with a lambda expression");
}

// Output:
//0 1 2 3 4 5 6 7 8 9 : sorted with the default operator<
//9 8 7 6 5 4 3 2 1 0 : sorted with the standard library compare function object
//0 1 2 3 4 5 6 7 8 9 : sorted with a custom function object
//9 8 7 6 5 4 3 2 1 0 : sorted with a lambda expression
Source by en.cppreference.com #
 
PREVIOUS NEXT
Tagged:
ADD COMMENT
Topic
Name
1+2 =