Is there a compact equivalent to Python range() in C++/STL

后端 未结 10 847
[愿得一人]
[愿得一人] 2020-12-04 21:23

How can I do the equivalent of the following using C++/STL? I want to fill a std::vector with a range of values [min, max).

# Python
>>>         


        
相关标签:
10条回答
  • 2020-12-04 22:09

    I don't know of a way to do it like in python but another alternative is obviously to for loop through it:

    for (int i = range1; i < range2; ++i) {
        x.push_back(i);
    }
    

    chris's answer is better though if you have c++11

    0 讨论(0)
  • 2020-12-04 22:10

    In C++11, there's std::iota:

    #include <vector>
    #include <numeric> //std::iota
    
    std::vector<int> x(10);
    std::iota(std::begin(x), std::end(x), 0); //0 is the starting number
    
    0 讨论(0)
  • 2020-12-04 22:10

    If you can't use C++11, you can use std::partial_sum to generate numbers from 1 to 10. And if you need numbers from 0 to 9, you can then subtract 1 using transform:

    std::vector<int> my_data( 10, 1 );
    std::partial_sum( my_data.begin(), my_data.end(), my_data.begin() );
    std::transform(my_data.begin(), my_data.end(), my_data.begin(), bind2nd(std::minus<int>(), 1));
    
    0 讨论(0)
  • 2020-12-04 22:17

    For those who can't use C++11 or libraries:

    vector<int> x(10,0); // 0 is the starting number, 10 is the range size
    transform(x.begin(),x.end(),++x.begin(),bind2nd(plus<int>(),1)); // 1 is the increment
    
    0 讨论(0)
提交回复
热议问题