Loop by use of `:` specification and/or definition

What exactly is a c++ loop by use of : definition, how define its upper limit?
is its equivalent to the common loop

1
2
3
4
5
6
7
8
for (int i=0; i<5; ++i) {
 cout << i ;
}

int n[]={1,2,3,4,5};
for (int i : n)
  cout << i ;
?


and to get even more obscure to understand one's c++ code seen sort of:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class D {
// ??? (his/her code not yet searched, found)
}

class M {
  D * a;
public:
  M( D & u) : a( &u) {}

}

D a;
for (int i : M(a))
  cout << i ;


so definitive determination on its lower,upper limit?
Please help out. Thanks
Last edited on
You are describing a "for-each" loop, something C++11 added to the toolbox.

The boundaries of a for-each loop are the beginning and the end of the array, and the loop accesses each element of the array.

https://www.learncpp.com/cpp-tutorial/for-each-loops/

The for-each loop is also known as a "range-based" for loop:

https://en.cppreference.com/w/cpp/language/range-for

Personally I find a range-based for loop much easier to understand and type than a regular for loop, especially if using iterators. An iterator for loop can be a major mess trying to type and read. Especially without using auto.
Last edited on
the : operator has multiple uses.
the first is the loop described above.
the second colon usage is a class initializer list, see https://en.cppreference.com/w/cpp/language/constructor

so a local object M is created from the D class object (a) which is used to initialize it, and the for loop iterates over the created object. the a object probably should have some values and the M class needs to be something that allows iteration, for all that to work.
As described in that cppreference page, the
1
2
3
4
for ( int i : n )
{
  cout << i ;
}

is roughly equivalent to
1
2
3
4
5
6
auto e = end(n);
for ( auto b = begin(n); b != end(n); ++b )
{
  auto i = *b;
  cout << i ;
}



That other code is more interesting:
1
2
D a;
for (int i : M(a)) cout << i ;

could be written:
1
2
3
D a;
M temp(a)
for (int i : temp) cout << i ;

The temp is a class object, not an array.
You don't show members begin() and end() in M.
Hence the loop can't expand like:
1
2
3
4
5
6
auto e = end(n);
for ( auto b = temp.begin(); b != temp.end(); ++b )
{
  auto i = *b;
  cout << i ;
}

Hence there must be (in your program) standalone begin() and end() that accept object of type M as parameter.
Topic archived. No new replies allowed.