3

Currently I'm initializing a list/vector etc. like this:

std::vector<int> vec_rand(target_size);
std::generate(vec_rand.begin(), vec_rand.end(), std::rand);

.. as already shown here. std::rand is just an example - it could be any function.

I was just wondering if there's a way to create/resize a container and initialize it's values with arbitrary values at the same time.

I know I don't have to expect a big performance boost but It would be nicer (and less verbose) to have s.th. like

vector<int> my_list(10, std::rand);

or

my_list.resize(target_size, std::rand);

rather than to first resize() with default values and than overwrite them with the desired content.

Community
  • 1
  • 1
frans
  • 8,868
  • 11
  • 58
  • 132
  • 3
    `vector::reserve()` followed by `std::generate_n` with a `back_inserter` ? – Jonathan Potter Dec 07 '15 at 10:21
  • @JonathanPotter seems reasonable. Make it an answer if you please. Close to the *same time* OP asked. – Marco A. Dec 07 '15 at 10:23
  • +1 because it would solve the issue with unnecessary initialization. But it's not an answer yet because you are still verbose (even more). – frans Dec 07 '15 at 10:28
  • @frans I don't think the standard allows for this in the constructor. Get yourself appointed to the standards committee and do something about it :) – Jonathan Potter Dec 07 '15 at 10:29

2 Answers2

6

This isn't possible in the constructor (or in a single instruction).

You can use vector::reserve() to allocate the memory (without initialising), and then std::generate_n with a back_inserter to fill the array.

my_list.reserve(target_size);
std::generate_n(std::back_inserter(my_list), target_size, std::rand);
Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79
1

The C++ standard vector resize function exists in two overloaded versions (since C++11), one taking simply the new size, and one taking the new size and a default value.

So it is not directly possible using only the resize function, buy if you wanted to make the code less verbose, you could create a wrapper function that did it. As you said yourself, it would not be the biggest performance boost anyway.

You could perhaps even make your own type, that was initialised with a value created by your randomise function, and castable to an int.

Edit: Jonathan Potter's comment could be an acceptable possibility.

Tommy Andersen
  • 7,165
  • 1
  • 31
  • 50