Create a discrete distribution from transformed container elements

Viewed 63

Suppose we have a std::vector<T> v and T is a class with a member function U T::f() const, where U is convertible to double. I want to create a std::discrete_distribution<> d(/* v[0].f(), ..., v[v.size() - 1].f() */). Is this possible without creating a new container containing the values v[0].f(), ..., v[v.size() - 1].f()?

2 Answers

If you can add a operator double to T then you can have that return f() and then use the iterator constructor of std::discrete_distribution like

struct Foo
{
    operator double() const { return f(); }
    double f() const { return 1.0; }
};

int main()
{
    std::vector<Foo> foo(10);
    std::discrete_distribution dd{foo.begin(), foo.end()};
}
Related