Emre
Emre

Reputation: 6227

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.

Upvotes: 16

Views: 3436

Answers (3)

Saksham
Saksham

Reputation: 9380

You can use std::transform as well

vector<int> vec(10,1);
transform(vec.begin(), vec.end(), vec.begin(), func);

Where func is:

int func(int i)
{
//return a random generated number 
}

Upvotes: 0

Cedric
Cedric

Reputation: 1

Encapsulate your initialization into a function and declare it "constexpr" so that you can use it to initialize a const expression.

Upvotes: 0

stijn
stijn

Reputation: 35901

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; 
  }() );

Upvotes: 25

Related Questions