use std::fill to populate vector with increasing numbers

后端 未结 15 890
深忆病人
深忆病人 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:17

    brainsandwich and underscore_d gave very good ideas. Since to fill is to change content, for_each(), the simplest among the STL algorithms, should also fill the bill:

    std::vector v(10);
    std::for_each(v.begin(), v.end(), [i=0] (int& x) mutable {x = i++;});    
    

    The generalized capture [i=o] imparts the lambda expression with an invariant and initializes it to a known state (in this case 0). the keyword mutable allows this state to be updated each time lambda is called.

    It takes only a slight modification to get a sequence of squares:

    std::vector v(10);
    std::for_each(v.begin(), v.end(), [i=0] (int& x) mutable {x = i*i; i++;});
    

    To generate R-like seq is no more difficult, but note that in R, the numeric mode is actually double, so there really isn't a need to parametrize the type. Just use double.

提交回复
热议问题