1. range-based for Loops
for (Decl:coll) {
Statement
}
eg
for int 2 3 5 7 9 - - + }) { << i << Std::endl;}
std::vector<Double> vec, ... . for (auto& Elem:vec) { 3;}
Here, declaring Elem as a reference are important because otherwise the statements in the body of the For Loop Act on a Loc Al copy of the elements in the vector (which sometimes also might is useful).
This means, avoid calling the copy constructor and the destructor for each element, you should usually declare the The current element is a constant reference. Thus, a generic function to print all elements of a collection should is implemented as follows:
Template <typename t>void printelements (const t& coll) { for ( Const auto& elem:coll) { << elem << Std::endl;} }
That section of the range-based for loops code is equivalent to the following:
for (Auto _pos=coll.begin (); _pos! = Coll.end (); + +_pos ) {const auto& elem = *_pos;
<< elem << Std::endl;}
intArray[] = {1,2,3,4,5 };Longsum=0;//process sum of all elements for(intx:array) {Sum+=x;} for(auto Elem: {sum, sum*2, sum*4} ) {//PrintStd::cout << Elem <<Std::endl;}
Some new features of c++11 language-range-based for Loops