Range based for loop in cpp

The below code snippet is python range based for loop with the increment of steps by 2.

1
2
  for x in range(1,10,2):        Result:1,3,5,7,9
    print(x)   


What is the equivalent range based for loop in cpp which includes steps.

Thank you!
I'm assuming range(1,10,2) means take all numbers between 1 and 10 that are not divisible by 2?

1
2
3
4
5
for(int i = 1; i <= 10; i++)
{
      if(i%2==1)
          std::cout << i;
}
No... here its not the concept of divisibility. It should print the numbers in the list based on the steps we give.

Ex: Here the step is 0.5, begin value=0.5, end value =2.5....range (0.5, 2.5,0.5) -Result: 0.5,1.0,1.5,2.0

Thank you!
for ( int x = 1; x < 10; x += 2 ) std::cout << x << '\n';

@zapshe, it doesn't include 10, and, by default, the python print statement will force a new line.

@Shruthi, a range-based for loop in c++ implies iterating through a whole (existing) container. In python it is a generator object. Despite the "range" they are very different things.
@lastchance, Thank you so much for explaining the difference between the two. It helped me a lot.
That makes more sense, stupid of me.
C++20 adds range library.
Example in: https://www.modernescpp.com/index.php/c-20-pythonic-with-the-ranges-library

Thus, apparently python's range( begin, end, stepsize ) in C++:
1
2
3
4
5
auto boundary = [end](int i){ return i < end; };

ranges::views::iota(begin)
    | ranges::views::stride(stepsize)
    | ranges::views::take_while(boundary))

(IF begin < end)
Last edited on
Don't these "modern" languages make things complicated!

print *, ( i, i = 1, 9, 2 )


or, if you require the newline:
print "(i0)", ( i, i = 1, 9, 2 )
Last edited on
Thank you all for your replies.
You may use C++17 and overload of << operator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <cassert>

using namespace std;

template<  typename T , char delimeter >
struct Format
{
    Format( T begin_ , T end_ , T stride_ )
    : begin {begin_} , end {end_} , stride {stride_}
    {
        assert( begin<=end && begin>=0 && end>=0 && stride>0 );
    }
    T begin {0};
    T end {0};
    T stride {1};
};

template< typename T, auto delimeter >
ostream& operator<<( ostream& out , const Format<T,delimeter>& format )
{
    for( auto index {format.begin} ; index<=format.end ; index+=format.stride )
    {
        out << index << ((index+format.stride>=format.end)?' ':delimeter);
    }
    out << endl;
    return out;
}

template< char delimeter = ' ' , typename T >
Format<T,delimeter> print( T start , T end , T stride = 1 )
{
    return {start,end,stride};
}

int main()
{
    cout << print<','>(1,10,2) << print(1,5) << print<'-'>(0.1,0.9,0.1);
    return 0;
}

https://wandbox.org/permlink/X7cOccjp4prZn16D
Topic archived. No new replies allowed.