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

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

    There is boost::irange, but it does not provide floating point, negative steps and can not directly initialize stl containers.

    There is also numeric_range in my RO library

    In RO, to initialize a vector:

    vector V=range(10);
    

    Cut-n-paste example from doc page (scc - c++ snippet evaluator):

    // [0,N)  open-ended range. Only range from 1-arg  range() is open-ended.
    scc 'range(5)'
    {0, 1, 2, 3, 4}
    
    // [0,N]  closed range
    scc 'range(1,5)'
    {1, 2, 3, 4, 5}
    
    // floating point 
    scc 'range(1,5,0.5)'
    {1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5}
    
    // negative step
    scc 'range(10,0,-1.5)'
    {10, 8.5, 7, 5.5, 4, 2.5, 1}
    
    // any arithmetic type
    scc "range('a','z')"
    a b c d e f g h i j k l m n o p q r s t u v w x y z
    
    // no need for verbose iota. (vint - vector)
    scc 'vint V = range(5);   V' 
    {0, 1, 2, 3, 4}
    
    // is lazy
    scc 'auto NR = range(1,999999999999999999l);  *find(NR.begin(), NR.end(), 5)'
    5
    
    //  Classic pipe. Alogorithms are from std:: 
    scc 'vint{3,1,2,3} | sort | unique | reverse'
    {3, 2, 1}
    
    //  Assign 42 to 2..5
    scc 'vint V=range(0,9);   range(V/2, V/5) = 42;  V'
    {0, 1, 42, 42, 42, 5, 6, 7, 8, 9}
    
    //  Find (brute force algorithm) maximum of  `cos(x)` in interval: `8 < x < 9`:
    scc 'range(8, 9, 0.01) * cos  || max'
    -0.1455
    
    //  Integrate sin(x) from 0 to pi
    scc 'auto d=0.001;  (range(0,pi,d) * sin || add) * d'
    2
    
    //  Total length of strings in vector of strings
    scc 'vstr V{"aaa", "bb", "cccc"};  V * size ||  add'
    9
    
    //  Assign to c-string, then append `"XYZ"` and then remove `"bc"` substring :
    scc 'char s[99];  range(s) = "abc";  (range(s) << "XYZ") - "bc"'
    aXYZ
    
    
    // Hide phone number:
    scc "str S=\"John Q Public  (650)1234567\";  S|isdigit='X';  S"
    John Q Public  (XXX)XXXXXXX
    

提交回复
热议问题