Can't find documentation of ": " in for(... : ...)

This is my first encounter with it
1
2
3
//points is a vector
 for(int p: points)
  ost<<....<<endl;
Search for "range-based for loop".
range-based for loop; lots of languages have it https://en.cppreference.com/w/cpp/language/range-for

In your example, "int p" is a value copy for an element in the points container. Often you see this temporary variable as a reference to save a copy, but you don't save much for primitive types like integers.

more or less equivalent to
1
2
3
4
5
6
int p;
for(int i=0; i<points.size(); ++i)
{
    p = points[i];
    // do stuff with p
}


Useful for when you want to do something with the elements but don't care about the indices. Supported by nearly all STL containers and even C-style arrays.

Edit: also, usually you'd leave a space on each side of the colon to better show intent, as per the examples in the documentation I linked
Last edited on
Topic archived. No new replies allowed.