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

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

    I ended up writing some utility functions to do this. You can use them as follows:

    auto x = range(10); // [0, ..., 9]
    auto y = range(2, 20); // [2, ..., 19]
    auto z = range(10, 2, -2); // [10, 8, 6, 4]
    

    The code:

    #include 
    #include 
    
    template 
    std::vector range(IntType start, IntType stop, IntType step)
    {
      if (step == IntType(0))
      {
        throw std::invalid_argument("step for range must be non-zero");
      }
    
      std::vector result;
      IntType i = start;
      while ((step > 0) ? (i < stop) : (i > stop))
      {
        result.push_back(i);
        i += step;
      }
    
      return result;
    }
    
    template 
    std::vector range(IntType start, IntType stop)
    {
      return range(start, stop, IntType(1));
    }
    
    template 
    std::vector range(IntType stop)
    {
      return range(IntType(0), stop, IntType(1));
    }
    

提交回复
热议问题