[C ++ 11] 30 minutes to learn about the new features of C ++ 11

Source: Internet
Author: User
Tags tidy

Author: Wang Xuan Yi, source: http://www.cnblogs.com/neverdie/Reprinted, Please keep this statement. If you like this article, click [recommendation ]. Thank you!

 

Auto a; // error. auto derives the type through the initialization expression. If there is no initialization expression, the Type auto I = 1; auto d = 1.0 of a cannot be determined; auto str = "Hello World"; auto ch = 'a'; auto func = less <int> (); vector <int> iv; auto ite = iv. begin (); auto p = new foo () // type derivation for the custom type

Auto not only has the above applications, but it also plays a role in the template, for example, the following example:Processed ProductsIn this example, if you do not use auto, you must declare the Product template parameter:

template <typename Product, typename Creator>void processProduct(const Creator& creator) {    Product* val = creator.makeObject();    // do somthing with val}               .

If auto is used, you can write as follows:

template <typename Creator>void processProduct(const Creator& creator) {    auto val = creator.makeObject();    // do somthing with val}

The entire code becomes more neat and tidy after you discard the troublesome template parameters.

Decltype

Decltype is actually a bit like the inverse function of auto. auto allows you to declare a variable, while decltype can get the type from a variable or expression, with examples as follows:

int x = 3;decltype(x) y = x;

Someone will ask, where is the decltype utility? Let's continue with the above example.Processed ProductsIn this example, what should we do if we want to return the product? We can write as follows:

template <typename Creator>auto processProduct(const Creator& creator) -> decltype(creator.makeObject()) {    auto val = creator.makeObject();    // do somthing with val}
Nullptr

Nullptr is introduced to solve the ambiguity of NULL in the original C ++.New TypeBecause NULL actually represents 0,

Void F (int a) {cout <a <endl;} void F (int * p) {assert (p! = NULL); cout <p <endl ;}int main () {int * p = nullptr; int * q = NULL; bool equal = (p = q ); // The value of equal is true, indicating that both p and q are null pointers int a = nullptr; // If compilation fails, nullptr cannot be converted to int F (0 ); // compilation fails in C ++ 98, which has two meanings. In C ++ 11, F (int) F (nullptr); return 0;} is called ;}
Sequence for Loop

In C ++, a simplified for loop similar to java can be used to traverse arrays, containers, strings, and sequences defined by the begin and end functions (that is, Iterator ), the sample code is as follows:

map<string, int> m{{"a", 1}, {"b", 2}, {"c", 3}};for (auto p : m){    cout<<p.first<<" : "<<p.second<<endl;}
Lambda expressions

Lambda expressions are similar to closures in Javascript. They can be used to create and define anonymous function objects to simplify programming. Lambda Syntax:

[Function object parameters] (operator overload function parameters)-> return value type {function body}

vector<int> iv{5, 4, 3, 2, 1};int a = 2, b = 1;for_each(iv.begin(), iv.end(), [b](int &x){cout<<(x + b)<<endl;}); // (1)for_each(iv.begin(), iv.end(), [=](int &x){x *= (a + b);});     // (2)for_each(iv.begin(), iv.end(), [=](int &x)->int{return x * (a + b);});// (3)
  • Parameters in [] refer to parameters that can be obtained by Lambda expressions.Global Variables. (1) function B refers to the function that can be obtained outside the Lambda expression.Global VariablesIf = is input in [], all external variables can be obtained, such as (2) and (3) Lambda expressions.
  • The parameters in () are called each time.Parameters passed in when the function is used.
  • -> Added the Lambda expression.Type of Return ValueFor example, (3) returns an int type variable.
Variable-length parameter Template

We have used pair in C ++. pair can be constructed using make_pair to construct a container containing two different types of data. For example, the following code:

auto p = make_pair(1, "C++ 11");

Since the variable length parameter template was introduced in C ++ 11, a new data type was invented: tuple, which is an N-tuples and can be imported into one, two or more data types

auto t1 = make_tuple(1, 2.0, "C++ 11");auto t2 = make_tuple(1, 2.0, "C++ 11", {1, 0, 2});

This avoids the ugly practice of nesting pair in the previous pair, and makes the code more clean and tidy.

Another common example is the Print function. In C language, printf can input multiple parameters. In C ++ 11, we can use a variable-length parameter template to implement a more concise Print function.

template<typename head, typename... tail>void Print(Head head, typename... tail) {    cout<< head <<endl;    Print(tail...);}

 

Multiple parameters of different types can be input in Print, as follows:

Print(1, 1.0, "C++11");
More elegant Initialization Method

Before C ++ 11 is introduced, only Arrays can use the initialization list. To use the initialization list for other containers, you can only use the following methods:

int arr[3] = {1, 2, 3}vector<int> v(arr, arr + 3);

In C ++ 11, we can use the following syntax to replace:

int arr[3]{1, 2, 3};vector<int> iv{1, 2, 3};map<int, string>{{1, "a"}, {2, "b"}};string str{"Hello World"};
Then...

If you want to learn more about the exciting new features of C ++ 11, I will recommend these two blogs to you:

Hu Jian's C ++ 11 series blog

ToWrting's C ++ 11 series blog

List of compiler support for C ++ 11

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.