Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you initialize a const vector of function results using C++11?

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.

like image 680
Emre Avatar asked Mar 05 '13 09:03

Emre


People also ask

What does a const vector mean in C++?

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.


1 Answers

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; 
  }() );
like image 107
stijn Avatar answered Oct 17 '22 13:10

stijn