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

后端 未结 10 901
[愿得一人]
[愿得一人] 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 21:55

    A range() function similar to below will help:

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    // define range function (only once)
    template 
    vector  range(T N1, T N2) {
        vector numbers(N2-N1);
        iota(numbers.begin(), numbers.end(), N1);
        return numbers;
    }
    
    
    vector  arr = range(0, 10);
    vector  arr2 = range(5, 8);
    
    for (auto n : arr) { cout << n << " "; }    cout << endl;
    // output:    0 1 2 3 4 5 6 7 8 9
    
    for (auto n : arr2) { cout << n << " "; }   cout << endl;
    // output:    5 6 7
    

提交回复
热议问题