use std::fill to populate vector with increasing numbers

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

    If you'd rather not use C++11 features, you can use std::generate:

    #include 
    #include 
    #include 
    
    struct Generator {
        Generator() : m_value( 0 ) { }
        int operator()() { return m_value++; }
        int m_value;
    };
    
    int main()
    {
        std::vector ivec( 10 );
    
        std::generate( ivec.begin(), ivec.end(), Generator() );
    
        std::vector::const_iterator it, end = ivec.end();
        for ( it = ivec.begin(); it != end; ++it ) {
            std::cout << *it << std::endl;
        }
    }
    

    This program prints 0 to 9.

提交回复
热议问题