Initialization of std::vector with a list of consecutive unsigned integers

前端 未结 5 1446
抹茶落季
抹茶落季 2020-12-16 03:45

I want to use a special method to initialize a std::vector which is described in a C++ book I use as a reference (the German book \'Der C++

5条回答
  •  没有蜡笔的小新
    2020-12-16 04:22

    there are at least three ways that you can do that. One was mentioned earlier by Brian

    //method 1
    generate(v.begin(), v.end(), [] { static int i {1}; return i++; });     
    

    You can also use std::iota if you are using c++11

    //method 2
    iota(v.begin(), v.end(), 1);
    

    Or instead you can initialize your container with 1s and then do a partial sum on that. I don't think anybody will use this third method anyway :)

    //method 3
    vector v(n, 1);                                                     
    partial_sum(v.begin(), v.end(), v.begin()); 
    

提交回复
热议问题