use std::fill to populate vector with increasing numbers

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

    Preferably use std::iota like this:

    std::vector v(100) ; // vector with 100 ints.
    std::iota (std::begin(v), std::end(v), 0); // Fill with 0, 1, ..., 99.
    

    That said, if you don't have any c++11 support (still a real problem where I work), use std::generate like this:

    struct IncGenerator {
        int current_;
        IncGenerator (int start) : current_(start) {}
        int operator() () { return current_++; }
    };
    
    // ...
    
    std::vector v(100) ; // vector with 100 ints.
    IncGenerator g (0);
    std::generate( v.begin(), v.end(), g); // Fill with the result of calling g() repeatedly.
    

提交回复
热议问题