use std::fill to populate vector with increasing numbers

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

    In terms of performance you should initialize the vector with use of reserve() combined with push_back() functions like in the example below:

    const int numberOfElements = 10;
    
    std::vector<int> data;
    data.reserve(numberOfElements);
    
    for(int i = 0; i < numberOfElements; i++)
        data.push_back(i);
    

    All the std::fill, std::generate, etc. are operating on range of existing vector content, and, therefore the vector must be filled with some data earlier. Even doing the following: std::vector<int> data(10); creates a vector with all elements set to its default value (i.e. 0 in case of int).

    The above code avoids to initialize vector content before filling it with the data you really want. Performance of this solution is well visible on large data sets.

    0 讨论(0)
  • 2020-12-02 10:25

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

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

    This program prints 0 to 9.

    0 讨论(0)
  • 2020-12-02 10:27

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

    vector<int> 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
    0 讨论(0)
提交回复
热议问题