std::ranges::generate_n

cppreference.com

Example

dice: type = {
    distr:  std::uniform_int_distribution<int> = (1, 6);
    device: std::random_device;
    engine: std::mt19937 = (device());

    roll: (inout this) -> int = {
        return distr(engine);
    }
}

main: () = {
    v: std::array<int, 8> = ();

    dice: dice = ();

    std::ranges::generate_n(v.begin(), v.size(), :() dice&$*.roll());
    std::println("{} (dice)", v);

    n: int = -1;
    std::ranges::generate_n(v.begin(), v.size(), :() n$++);
    std::println("{} (iota)", v);
}

Possible output

[4, 1, 6, 1, 6, 1, 1, 5] (dice)
[0, 1, 2, 3, 4, 5, 6, 7] (iota)

Back to top

cpp2reference.com licensed under CC-BY-SA and GFDL.