0

Why my lambda doesn't put elements in vector?

void generate_N_numbers_in_the_vector(std::vector<int> &vec, int &M,
                                      const int &N) {
  std::random_device rand;
  static std::mt19937 gen(rand());
  static std::uniform_int_distribution<int> distribution(0, M);
  vec.reserve(N);

  std::generate(vec.begin(), vec.end(), []() { return distribution(gen); });

  for (auto elem : vec) std::cout << elem << std::endl;
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Boski
  • 1
  • 2
    Because it is empty. Use `.resize()`. – Evg Jan 08 '20 at 19:20
  • 2
    Does this answer your question? [Choice between vector::resize() and vector::reserve()](https://stackoverflow.com/questions/7397768/choice-between-vectorresize-and-vectorreserve) – Evg Jan 08 '20 at 19:21
  • In modern C++ you better return that vector rather than pass it by reference - due to move semantics it is not less efficient but much more readable. For example it may solve your issue as a side effect (you probably would use proper ctor with size) – Slava Jan 08 '20 at 19:26
  • @Slava, it can be less efficient if this function is called repeatedly on the same vector. – Evg Jan 08 '20 at 19:29
  • @Evg then subject to the question should be "add random elements to a vector" instead of "fill vector..." – Slava Jan 08 '20 at 19:33

2 Answers2

4

When you use reserve the number of elements in the vector does not increase. That means that the difference between begin(vec) and end(vec) is 0 (or whatever the size of your vector was at the start). There are two possibilities:

vec.resize(N);
std::generate(vec.begin(), vec.end(), [](){return distribution(gen);});
// or
vec.reserve(N); // Not necessary but sensible.
std::generate_n(std::back_inserter(vec), N, [](){return distribution(gen);});
n314159
  • 4,990
  • 1
  • 5
  • 20
1

std::vector::reserve only reserves space, meaning increases the capacity, not the size. Use std::vector::resize instead to change the vector's size.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93