Jun 13, 2022

[C++] C++20 code examples

Reference:
https://www.youtube.com/watch?v=UCIKbUvEKfI


Ranges as Single Argument:

std::ranges::sort(coll);


https://en.cppreference.com/w/cpp/ranges/input_range
void print(const std::ranges::input_range auto& rg) {
    std::ranges::for_each(rg,
        [] (const auto& val) { ... });
}


Sentinels:
template<auto Val> // can be Non-Type Template Parameter(NTTP) parameters
struct EndValue{
// operator== introduces
// lhs == rhs
// rhs == lhs
// lhs != rhs
// rhs != lhs
    bool operator== (auto pos) const {
        return *pos == Val;
    }
};

std::vector coll = {42,32,12, -1, 2};

// no need as same type arguments
std::ranges::sort(coll.begin(), EndValue<-1>{});

std::ranges::subrange range{coll.begin(), EndValue<-1>{}};

print(range);
print(coll);

struct Coord {
    double x, y, z;

    // defines all 6 comparison operators
    // constexpr, noexcept, type conversions
    auto operator<=> (const Coord&) const = default;

    friend std::ostream& operator<< (std::ostream& strm, const Coord& c) {
        return strm << std::format("{}/{}/{}", c.x, c.y, c.z);
    }
};

std::array points{Coord{1,2,3}, Coord{4,5,6}, Coord{7,8,9}};
std::ranges::sort(points);
print(std::ranges::subrange{points.begin(), EndValue<Coord{4,5,6}>{}});


Views:
std::ranges::sort(std::views::counted(coll.begin(), 4));
print(coll);

// View is lazy evaluated. i.e vw is a composition of operation; not the result.
// only until its dereferenced does it doing calculation.
auto vw = coll | std::views::filter([] (const auto& v) { return v > 0; })
                            | std::views::transform([] (const auto& v) { return v*v; });

// https://en.cppreference.com/w/cpp/ranges/input_range
void print(std::ranges::input_range auto&& rg) {
    std::ranges::for_each(rg,
        [] (const auto& val) { ... });
}

print(vw); // this print has signature change to universal reference




Pipelines of Range Adaptors:
std::map<std::string, int> composer {
    {"A", 123}, {"B", 456},
};

namespace vws = std::views;

for (const auto& e : composer
    | vws::filter([](const auto& y) { return y.second >= 100;})
    | vws::take(3)
    | vws::keys) {

    ...
}



Threads:
// https://en.cppreference.com/w/cpp/thread/stop_token

#include <barrier>

void compute() {
    std::array values {1.0, 2.0, 3.0};

    std::barrier allRdy{ values.size(),
    	[&]()noexcept{print(values);}};

    std::vector<std::jthread> threads;

    for(auto idx = 0; idx < values.size(); ++idx) {
        threads.push_back(std::jthread{
            [idx, &values, &allRdy] (std::stop_token st) {
                while(!st.stop_requested()) {
                    values[idx] = std::sqrt(values[idx]);
                    ...
                    allRdy.arrive_and_wait(); // sync and print()
                }

                // ensure other threads don't wait for this anymore;
                arrRdy.arrive_and_drop();

            }});
    }
}


// std::binary_semqphore
// https://en.cppreference.com/w/cpp/thread/counting_semaphore

int inData;
std::binary_semaphore inReady{0};

// start threads to read and process values by value:
std::jthread process{ [&] (std::stop_token st) {
    while(!st.stop_requested()) {
    if (inReady.try_acquire_for(1s)) {
        int data = inData;
        ...

    }}};


for (int i = 0; i < 10; ++i) {
    inData = i;
    inReady.release();
}
std::atomic_ref<> useful for make value atomic in certain scope but not the value itself is atomic.
std::atomic now can be used as conditional variable and it is FAIR scheduled.

// std::atomic<>
// https://en.cppreference.com/w/cpp/atomic/atomic/notify_one
std::atomic.wait();



Chrono:
auto fst = 2021y / 1 / 1;
auto lst = 2021y / 12 / std::chrono::last;

// std::chrono::sys_days
for (auto d = fst; d <= lst; d+= std::chrono::months{1}) {
    std::chrono::weekday{d} == std::chrono::Monday;

}


Time zones:


#include <chrono>
auto localNow = std::chrono::current_zone() -> to_local(std::chrono::system_clock::now());
std::chrono::year_month_day{std::chrono::floor<std::chrono::days>(localNow)};

// clocks
// system_clock
// utc_clock
// gps_clock
// tai_clock
// ----

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.