C ++ 11 to make simple things simple

Source: Internet
Author: User

C ++ 11 to make simple things simple

Joe Armstrong said:

The problem with object-oriented programming language is that it always comes with all the implied environments it needs. You want a banana, but you get a gorilla with a banana and the whole jungle.

Obviously, this will complicate the simple problem. We do not deny that some code in this world cannot be simplified. For code that can be simplified, we still hope it will not be complicated. If you are such a person, there is no reason not to use C ++ 11. The following shows how C ++ 11 miraculously simplifies the code.

Assume that the following code is used to determine whether there is a string in the container that meets our requirements:

vector
  
   ::const_iterator cit = vs.cbegin();for (; cit != vs.end(); ++cit) {    if (lookForParttern(*cit))        return true;}return false;
  

Before C ++ 11, this code is too common. With C ++ 11, we can easily write the following code:

for (auto cit = vs.cbegin(); cit != vs.end(); ++cit) {    if (lookForParttern(*cit))        return true;}return false;

For is better than the previous one. This code looks more elegant. C ++ has a range-for, so we can write it like this:

for (auto& x : vs) {    if (lookForParttern(x))        return true;}return false;

I found it concise. This is not enough. We can also use algorithms to make the code more concise:

return find_if(cbegin(vs), cend(vs), lookForParttern) != cend(vs);

Well, it turns into a line of code. To be honest, it is also annoying to write too much about cbegin and cend. We can use the range algorithm to eliminate it:

return find_if(vs, lookForParttern) != cend(vs);

Compared with the first piece of code, not only is the code much shorter, but it is also readable. C ++ 11 greatly improves productivity without reducing operation efficiency. You can throw Java and C # aside.

 

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.