A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://en.cppreference.com/w/cpp/algorithm/../symbol_index/../algorithm/ranges/generate_n.html below:

std::ranges::generate_n - cppreference.com

Assigns the result of successive invocations of the function object gen to each element in the range [firstfirst + n), if 0 < n. Does nothing otherwise.

The function-like entities described on this page are algorithm function objects (informally known as niebloids), that is:

[edit] Parameters first - the beginning of the range of elements to modify n - number of elements to modify gen - the generator function object. [edit] Return value

Iterator one past the last element assigned if 0 < count, first otherwise.

[edit] Complexity

Exactly n invocations of gen() and assignments.

[edit] Possible implementation [edit] Example
#include <algorithm>
#include <array>
#include <iostream>
#include <random>
#include <string_view>
 
auto dice()
{
    static std::uniform_int_distribution<int> distr {1, 6};
    static std::random_device engine;
    static std::mt19937 noise {engine()};
    return distr(noise);
}
 
void print(const auto& v, std::string_view comment)
{
    for (int i : v)
        std::cout << i << ' ';
    std::cout << '(' << comment << ")\n";
}
 
int main()
{
    std::array<int, 8> v;
 
    std::ranges::generate_n(v.begin(), v.size(), dice);
    print(v, "dice");
 
    std::ranges::generate_n(v.begin(), v.size(), [n {0}] mutable { return n++; });
    // same effect as std::iota(v.begin(), v.end(), 0);
    print(v, "iota");
}

Possible output:

5 5 2 2 6 6 3 5 (dice)
0 1 2 3 4 5 6 7 (iota)
[edit] See also saves the result of a function in a range
(algorithm function object)[edit] fills a range with random numbers from a uniform random bit generator
(algorithm function object)[edit] assigns a range of elements a certain value
(algorithm function object)[edit] assigns a value to a number of elements
(algorithm function object)[edit] applies a function to a range of elements
(algorithm function object)[edit] assigns the results of successive function calls to N elements in a range
(function template) [edit]

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4