c++每调用一次函数+1_每个开发人员都应该知道的一些很棒的现代C ++功能

c++每调用一次函数+1

As a language, C++ has evolved a lot.

作为一种语言,C ++已经发展了很多。

Of course this did not happen overnight. There was a time when C++ lacked dynamism. It was difficult to be fond of the language.

当然,这并非一overnight而就。 曾经有一段时间,C ++缺乏活力。 很难喜欢这种语言。

But things changed when the C++ standard committee decided to spin up the wheel.

但是,当C ++标准委员会决定加快发展时,事情发生了变化。

Since 2011, C++ has emerged as a dynamic and ever-evolving language that a lot of people have been hoping for.

自2011年以来,C ++已经成为许多人一直期望的动态且不断发展的语言。

Don’t get the wrong idea that the language has become easier. It still is one of the hardest programming languages, if not the hardest one, that are used widely. But C++ has also become much more user friendly than its previous versions.

不要误以为语言变得更容易了。 它仍然是使用最广泛的最困难的编程语言之一,即使不是最困难的一种。 但是C ++也比以前的版本更加易于使用。

In my last post, I talked about the C++ algorithm library that has been enriched over the last couple of years.

在我的上一篇文章中,我谈到了在过去几年中得到了丰富的C ++算法库

Today, we shall look into some new features (starting from C++11, which is already 8 years old by the way) that every developer would like to know.

今天,我们将研究每个开发人员都想知道的一些新功能(从C ++ 11开始,已经有8年的历史了)。

Also note that I have skipped some advanced features in this article, but I’m willing to write about them in future. ?️

还要注意,我在本文中略过了一些高级功能,但是以后我愿意写这些功能。 ️️

Go!

走!

自动关键字 (The auto keyword)

When C++11 first introduced auto, life became easier.

当C ++ 11首次引入auto ,生活变得更加轻松。

The idea of auto was to make the C++ compiler deduce the type of your data while compiling — instead of making you declare the type every-freaking-time. That was so convenient when you have data types like map<string,vector<pair<int,int>>> ?

auto的想法是让C ++编译器在编译时推断出数据的类型—而不是让您每次都在声明类型 当您具有map<string,vector<pair<i nt,int >>>之类的数据类型时,这非常方便。

Look at the line number 5. You cannot declare something without an initializer. That actually makes sense. Line 5 doesn’t let the compiler know what can the data type be.

查看行号5。没有initializer您无法声明某些内容。 这实际上是有道理的。 第5行不让编译器知道数据类型可以是什么。

Initially, auto was somewhat limited. Then in the later versions of the language, more power was added to it!

最初, auto受到一定限制。 然后在该语言的更高版本中,添加了更多功能!

In lines 7 and 8, I used bracketed initialization. This was also a new feature added in C++11.

在第7和8行中,我使用了括号初始化。 这也是C ++ 11中添加的新功能。

Remember, in case of using auto, there must be some way for the compiler to deduce your type.

请记住,在使用auto情况下,编译器必须采用某种方式来推断您的类型。

Now a very nice question, what happens if we write auto a = {1, 2, 3}? Is that a compile error? Is that a vector?

现在是一个很好的问题, 如果我们写 auto a = {1, 2, 3}会发生什么 ? 那是编译错误吗? 那是向量吗?

Actually, C++11 introduced std::initializer_list<type>. Braced initialized list will be considered as this lightweight container if declared auto.

实际上,C ++ 11引入了std::initializer_list<ty pe>。 支撑初始化列表将被视为如果这个月轻量级容器lare d汽车。

Finally, as I previously mentioned, type-deducing by compiler can be really useful when you have complex data structures:

最后,正如我之前提到的,当您具有复杂的数据结构时,由编译器进行类型推导非常有用:

Don’t forget to check out line 25! The expression auto [v1,v2] = itr.second is literally a new feature in C++17. This is called structured binding. In previous versions of the language, you had to extract each variable separately. But structured binding has made it much more convenient.

不要忘记签出第25行! auto [v1,v2] = itr.second实际上是C ++ 17中的新功能。 这称为结构化绑定 。 在该语言的早期版本中,您必须分别提取每个变量。 但是结构化绑定使其更加方便。

Moreover, if you wanted to get the data using reference, you would just add a symbol — auto &[v1,v2] = itr.second.

此外,如果要使用引用获取数据,只需添加一个符号— auto &[v1,v2] = itr.second

Neat.

整齐。

Lambda表达式 (The lambda expression)

C++11 introduced lambda expressions, something like anonymous functions in JavaScript. They are function objects, without any names, and they capture variables on various scopes based on some concise syntax. They are also assignable to variables.

C ++ 11引入了lambda表达式,类似于JavaScript中的匿名函数。 它们是函数对象,没有任何名称,并且它们基于一些简洁的语法在各种范围内捕获变量。 它们也可以分配给变量。

Lambdas are very useful if you need some small quick thing to be done inside your code but you are not willing to write a whole separate function for that. Another pretty common use is to use them as compare functions.

如果您需要在代码中完成一些小的快速操作,但是您不愿意为此编写一个完整的单独函数,则Lambda非常有用。 另一个很常见的用途是将它们用作比较功能。

The above example has a lot to say.

上面的例子有很多话要说。

Firstly, notice how curly braced initialization is lifting the weight for you. Then comes generic begin(), end() that is also an addition in C++11. Then comes the lambda function as a comparator for you data. The parameters of the lambda function are declared auto which was added in C++14. Before that, we could not use auto for function parameters.

首先,请注意花括号初始化如何为您增加负担。 然后是通用的begin(), end() ,这也是C ++ 11中的附加功能。 然后,lambda函数用作数据的比较器。 lambda函数的参数声明为auto 这是在C ++ 14中添加的。 在此之前,我们不能使用auto作为函数参数。

Note how we start the lambda expression with a square bracket []. They define the scope of the lambda — how much authority it has over the local variables and objects.

请注意我们如何使用方括号[]启动lambda表达式。 它们定义了lambda的范围-它对局部变量和对象有多少权限。

As defined in this awesome repository on modern C++:

正如现代C ++上这个出色的存储库中所定义的:

  • [] — captures nothing. So you cannot use any local variable of the outer scope inside your lambda expression. You can only use the parameters.

    [] -不捕获任何内容。 因此,您不能在lambda表达式内使用外部作用域的任何局部变量。 您只能使用参数。

  • [=] — captures local objects (local variables, parameters) in scope by value. You can use them, but cannot modify them.

    [=] -按值捕获范围内的局部对象(局部变量,参数)。 您可以使用它们,但不能修改它们。

  • [&] — capture local objects (local variables, parameters) in scope by reference. You can modify them. Like the following example.

    [&] —通过引用捕获作用域中的局部对象(局部变量,参数)。 您可以修改它们。 像下面的例子。

  • [this] — capture this pointer by value.

    [this] -按值捕获this指针。

  • [a, &b] — capture objects a by value, b by reference.

    [a, &b] -按值捕获对象a ,按引用捕获对象b

So if, inside your lambda function, you want to transform your data into some other format, you can use lambda by taking the advantage of the scoping. For example:

因此,如果您想在lambda函数中将数据转换为其他格式,则可以利用作用域的优势来使用lambda。 例如:

In the above example, if you had captured local variables by value ([factor]) in your lambda expression, you could not change factor in line 5. Because simply, you have no right to do that. Don’t misuse your rights! ?

在上面的示例中,如果您在lambda表达式中通过值( [factor] )捕获了局部变量,则无法在第5行中更改factor 。因为简单来说,您无权执行此操作。 不要滥用您的权利! ?

Finally, notice that we take val as reference. This ensures that any change inside the lambda function actually changes the vector.

最后,请注意,我们以val为参考。 这样可以确保lambda函数内部的任何更改实际上都会更改vector

if和switch内部的init语句 (Init statements inside if & switch)

I really liked this feature of C++17 immediately after I got to know of it.

我一开始就很喜欢C ++ 17的这个功能。

So apparently, now you can do initialization of variables and check condition on that — simultaneously inside the if/switch block. This is really helpful to keep your code concise and clean. The general form is:

因此,很显然,现在您可以在if/switch块中同时进行变量的初始化和检查条件。 这对于使代码简洁明了非常有帮助。 通用形式为:

if( init-statement(x); condition(x)) {
    // do some stuff here
} else {
    // else has the scope of x
    // do some other stuff
}
在constexpr的编译时完成 (Do it in compile time by constexpr)

constexpr is cool!

constexpr很酷!

Say you have some expression to evaluate and its value won’t change once initialized. You can pre-calculate the value and then use it as a macro. Or as C++11 offered, you can use constexpr.

假设您有一些要评估的表达式,并且初始化后其值不会改变。 您可以预先计算该值,然后将其用作宏。 或如提供的C ++ 11一样,可以使用constexpr

Programmers tend to reduce runtime of their programs as much as possible. So if there are some operations you can make the compiler do and take the load off runtime, then the runtime can be improved.

程序员倾向于尽可能减少其程序的运行时间。 因此,如果有一些操作可以使编译器完成并减轻运行时的负担,则可以改善运行时。

The above code is a very common example of constexpr.

上面的代码是constexpr的非常常见的示例。

Since we declared the fibonacci calculation function as constexpr, the compiler can pre-calculate fib(20) in compile time. So after compilation, it can replace the line

由于我们将fibonacci计算函数声明为constexpr ,因此编译器可以预先计算fib(20) 在编译时。 所以编译后就可以替换行

const long long bigval = fib(20); with

const long long bigval = fib(20);

const long long bigval = 2432902008176640000;

const long long bigval = 2432902008176640000;

Note that the passed argument is a const value. This is one important point of functions declared constexpr — the arguments passed should also be constexpr or const. Otherwise, the function will behave as a normal function which means no pre-calculation during compile time.

请注意,传递的参数是const值。 这是声明为constexpr的函数的重要一点-传递的参数也应该为constexprconst 。 否则,该函数将表现为普通函数,这意味着在编译期间不会进行任何预先计算。

Variables can also be constexpr, too. In that case, as you can guess, those variables have to be evaluable in compile time. Otherwise, you get a compilation error.

变量也可以是constexpr 。 如您所料,在那种情况下,这些变量必须在编译时可计算。 否则,您将收到编译错误。

Interestingly, later in C++17, constexpr-if and constexpr-lambda were introduced.

有趣的是,稍后在C ++ 17中,使用constexpr-ifconstexpr-lambda 被介绍了。

元组 (Tuples)

Much like pair, tuple is a collection of fixed size values of various data types.

pair相似, tuple是各种数据类型的固定大小值的集合。

Sometimes it is more convenient to use std::array instead of tuple. array is similar to plain C type array along with couple of functionalities of the C++ standard library. This data structure was added in C++11.

有时使用std::array代替tuple更方便。 array与普通的C类型数组相似,并具有C ++标准库的几个功能。 此数据结构是在C ++ 11中添加的。

类模板参数推导 (Class template argument deduction)

A very verbose name for a feature. The idea is, from C++17, argument deduction for templates will also happen for standard class templates. Previously, it was supported for only function templates.

功能的非常冗长的名称。 这个想法是,从C ++ 17开始,标准类模板也将进行模板的参数推导。 以前,仅功能模板支持该功能。

As a result,

结果是,

std::pair<std::string, int> user = {"M", 25}; // previous
std::pair user = {"M", 25}; // C++17

The type of deduction is done implicitly. This becomes even more convenient for tuple.

扣除类型是隐式完成的。 对于tuple这变得更加方便。

// previous
std::tuple<std::string, std::string, int> user ("M", "Chy", 25);
// deduction in action! 
std::tuple user2("M", "Chy", 25);

This feature above won’t make any sense if you are not quite familiar with C++ templates.

如果您不太熟悉C ++模板,则上述功能将毫无意义。

智能指针 (Smart pointers)

Pointers can be hellish.

指针可能是地狱般的。

Due to the freedom that languages like C++ provide to programmers, it sometimes becomes very easy to shoot yourself in the foot. And in many cases, pointers are responsible for the harm.

由于C ++之类的语言为程序员提供的自由度,有时候使自己陷入困境非常容易。 在很多情况下,指针是造成危害的原因。

Luckily, C++11 introduced smart pointers, pointers that are far more convenient than raw pointers. They help programmers to prevent memory-leaks by freeing it when possible. They also provide exception safety.

幸运的是,C ++ 11引入了智能指针,这些指针比原始指针要方便得多。 它们通过尽可能释放内存来帮助程序员防止内存泄漏。 它们还提供异常安全性。

I thought of writing about the smart pointers in C++ in this post. But apparently, there are lots of important details about them. They deserve their own post and I am certainly willing to write one about them in near future.

我想在这篇文章中写有关C ++中的智能指针的文章。 但是显然,关于它们有很多重要的细节。 他们应有自己的职位,我当然愿意在不久的将来写一篇关于他们的文章。

That’s all for today. Remember that C++ actually added a lot more newer features in the latest versions of the language. You should check them out if you feel interested. Here is an awesome repository on modern C++ which is literally named Awesome Modern C++!

今天就这些。 请记住,C ++实际上在该语言的最新版本中添加了许多新功能。 如果您有兴趣,应该检查一下。 这是现代C ++上的一个很棒的存储库,其字面名称为Awesome Modern C ++

Adios!

阿迪奥斯!

翻译自: https://www.freecodecamp.org/news/some-awesome-modern-c-features-that-every-developer-should-know-5e3bf6f79a3c/

c++每调用一次函数+1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值