zoukankan      html  css  js  c++  java
  • 一些C++11语言新特性

    1. Range-Based for Loops

    for ( decl : coll ) {
     statement
    }

    eg:

    for ( int i : { 2, 3, 5, 7, 9, 13, 17, 19 } ) {
        std::cout << i << std::endl;
    }
    std::vector<double> vec;
    ...
    for ( auto& elem : vec ) {
        elem *= 3;
    }

    Here, declaring elem as a reference is important because otherwise the statements in the body of the for loop act on a local copy of the elements in the vector (which sometimes also might be useful).

    This means that to avoid calling the copy constructor and the destructor for each element, you should usually declare the current element to be a constant reference. Thus, a generic function to print all elements of a collection should be implemented as follows:

    template <typename T>
    void printElements (const T& coll)
    {
        for (const auto& elem : coll) {
            std::cout << elem << std::endl;
        }
    }

    那段range-based for loops代码等价于如下:

    for (auto _pos=coll.begin(); _pos != coll.end(); ++_pos ) {
        const auto& elem = *_pos;
        std::cout << elem << std::endl;
    }
    int array[] = { 1, 2, 3, 4, 5 };
    long sum=0; // process sum of all elements
    for (int x : array) {
        sum += x;
    }
    for (auto elem : { sum, sum*2, sum*4 } ) { // print 15 30 60
        std::cout << elem << std::endl;
    }
  • 相关阅读:
    百度点聚合功能,自定义针头功能
    iOS之极光推送
    iOS之短信认证
    iOS FMDB
    iOS 远程推送
    iOS之本地推送(前台模式与后台模式)
    iOS指纹识别
    关于——GCD
    关于——NSThread
    给label text 上色 && 给textfiled placeholder 上色
  • 原文地址:https://www.cnblogs.com/davidgu/p/4607897.html
Copyright © 2011-2022 走看看