use std::fill to populate vector with increasing numbers

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

    You should use std::iota algorithm (defined in ):

      std::vector ivec(100);
      std::iota(ivec.begin(), ivec.end(), 0); // ivec will become: [0..99]
    

    Because std::fill just assigns the given fixed value to the elements in the given range [n1,n2). And std::iota fills the given range [n1, n2) with sequentially increasing values, starting with the initial value and then using ++value.You can also use std::generate as an alternative.

    Don't forget that std::iota is C++11 STL algorithm. But a lot of modern compilers support it e.g. GCC, Clang and VS2012 : http://msdn.microsoft.com/en-us/library/vstudio/jj651033.aspx

    P.S. This function is named after the integer function from the programming language APL, and signifies a Greek letter iota. I speculate that originally in APL this odd name was chosen because it resembles an “integer” (even though in mathematics iota is widely used to denote the imaginary part of a complex number).

提交回复
热议问题