Is it possible to use something like generate_n
to create a const vector
of, say, random numbers? I couldn't think of a way to do it without deriving vector
and doing the assignment in the constructor.
A const vector will return a const reference to its elements via the [] operator . In the first case, you cannot change the value of a const int&. In the second case, you cannot change the value of a reference to a constant pointer, but you can change the value the pointer is pointed to.
Use a static helper or a lambda if you wish; move semantics / copy elision as pointed out in the comments will make this pretty cheap since all decent compilers will omit a full copy of the vector returned by the helper. Instead they'll just create the code to fill a single vector and then use that one.
std::vector< int > Helper()
{
const size_t n = 10;
std::vector< int > x( n );
std::generate_n( x.begin(), n, someGenerator );
return x;
}
const std::vector< int > my_const_vec( Helper() );
here is the lambda version:
const std::vector< int > my_const_vec( [] ()
{
const size_t n = 10;
std::vector< int > x( n );
std::generate_n( x.begin(), n, someGenerator );
return x;
}() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With