Some new features of c++11 language-range-based for Loops

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.