use std::fill to populate vector with increasing numbers

后端 未结 15 963
深忆病人
深忆病人 2020-12-02 09:32

I would like to fill a vector using std::fill, but instead of one value, the vector should contain numbers in increasing order after.

15条回答
  •  日久生厌
    2020-12-02 10:27

    There is another option - without using iota. For_each + lambda expression can be used:

    vector ivec(10); // the vector of size 10
    int i = 0;            // incrementor
    for_each(ivec.begin(), ivec.end(), [&](int& item) { ++i; item += i;});
    

    Two important things why it's working:

    1. Lambda captures outer scope [&] which means that i will be available inside expression
    2. item passed as a reference, therefore, it is mutable inside the vector

提交回复
热议问题