【cmu15445c++入门】(7)C++ auto 关键字

2024-02-06 22:28

本文主要是介绍【cmu15445c++入门】(7)C++ auto 关键字,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、auto关键字介绍

C++ auto 关键字是一个关键字,它告诉编译器通过其初始化表达式推断声明变量的类型。它可以提高开发人员的效率(开发人员不再需要输入冗长、不守规矩的类型名称)。它在 for-each 循环的上下文中也很有用。但是,使用 auto 会带来风险,因为开发人员可能不知道他们正在使用的类型,因此存在错误和非功能性代码的风险。所以要小心!

二、代码

// Includes std::cout (printing) for demo purposes.
#include <iostream>
// Includes the std::set library.
#include <set>
// Includes the C++ string library.
#include <string>
// Includes the std::vector library.
#include <vector>
// Includes the std::unordered map library.
#include <unordered_map>// The C++ auto keyword is a keyword that tells the compiler to infer the type
// of a declared variable via its initialization expression. It can be
// incredibly useful, as it allows for developer efficiency (where the developer
// no longer has to type out long, unruly type names). It is also useful in the
// context of for-each loops. However, using auto poses a risk where the
// developer may not be aware of the types they are using, and therefore at risk
// for buggy and non functional code. So be careful!// C++ auto 关键字是一个关键字,它告诉编译器通过其初始化表达式推断声明变量的类型。
// 它可以提高开发人员的效率(开发人员不再需要输入冗长、不守规矩的类型名称)。
// 它在 for-each 循环的上下文中也很有用。
// 但是,使用 auto 会带来风险,因为开发人员可能不知道他们正在使用的类型.
// 因此存在错误和非功能性代码的风险。所以要小心!// Basic templated class with very long name, to show the usefulness of auto.
template <typename T, typename U> class Abcdefghijklmnopqrstuvwxyz {
public:Abcdefghijklmnopqrstuvwxyz(T instance1, U instance2): instance1_(instance1), instance2_(instance2) {}void print() const {std::cout << "(" << instance1_ << "," << instance2_ << ")\n";}private:T instance1_;U instance2_;
};// Templated function that returns an object of this class with a very long
// name.
template <typename T>
Abcdefghijklmnopqrstuvwxyz<T, T> construct_obj(T instance) {return Abcdefghijklmnopqrstuvwxyz<T, T>(instance, instance);
}int main() {// The auto keyword is used to initialize the variable a. Here, the type// is inferred to be type int.auto a = 1;// Here are more examples of using auto to declare basic variables.// Depending on the IDE being used, it might say what types a, b, and c// are.auto b = 3.2;auto c = std::string("Hello");// auto is not particularly useful for these prior examples. As one can// see, typing int a = 1;, float b = 3.2;, and std::string c = "Hello";// does not take significant overhead. However, there will definitely// be cases where the type name is long and complicated, or when the// type name is heavily templated, and using auto may be helpful.Abcdefghijklmnopqrstuvwxyz<int, int> obj = construct_obj<int>(2);auto obj1 = construct_obj<int>(2);// Maybe for one line it does not seem all that convenient, but imagine// if using a class with a very long name was useful in the code for// an extended period of time. Then, I'd imagine it would save a lot of// typing time!// 也许对于一行来说,它似乎并不那么方便,但想象一下,如果使用一个名称很长的类在代码中很长一段时间内都很有用。然后,我想它会节省很多打字时间!// One important thing to note about the auto keyword is that it // defaults to copying objects, which can lower performance. Take the// following example where we construct a int vector, and want to// define a variable that is a reference to it.// 关于 auto 关键字需要注意的一件重要事情是,它默认用于复制对象,这可能会降低性能。// 以下面的例子为例,我们构造了一个 int 向量,并想要定义一个变量来引用它。std::vector<int> int_values = {1, 2, 3, 4};// The following code deep-copies int_values into copy_int_values,// since auto infers the type as std::vector<int>, not std::vector<int>&.// 下面的例子是个拷贝auto copy_int_values = int_values;// However, the following code defines ref_int_values, which is a reference// to int_values, and therefore does not deep copy the int_values vector.// 下面的例子是个引用auto& ref_int_values = int_values;// The auto keyword is also useful for iterating through C++ containers.// For instance, let's construct an unordered map with std::string keys// and int values, and discuss methods of iterating through it.std::unordered_map<std::string, int> map;map.insert({{"andy", 445}, {"jignesh", 645}});// One method mentioned in unordered_map.cpp was to iterate through// a map by using a for loop with an iterator. Compare the readability// of the two loops below.// 关于 auto 关键字需要注意的一件重要事情是,对于对象采用的是复制,这可能会降低性能。// 以下面的例子为例,我们构造了一个 int 向量,并想要定义一个变量来引用它。std::cout << "Printing elements in map...\n";for (std::unordered_map<std::string, int>::iterator it = map.begin();it != map.end(); ++it) {std::cout << "(" << it->first << "," << it->second << ")"<< " ";}std::cout << std::endl;std::cout << "Printing elements in map with auto...\n";for (auto it = map.begin(); it != map.end(); ++it) {std::cout << "(" << it->first << "," << it->second << ")"<< " ";}std::cout << std::endl;// It is also possible to use the auto keyword to iterate over vectors// and sets.std::vector<int> vec = {1, 2, 3, 4};std::cout << "Printing elements in vector with auto...\n";for (const auto& elem : vec) {std::cout << elem << " ";}std::cout << std::endl;std::set<int> set;for (int i = 1; i <= 10; ++i) {set.insert(i);}std::cout << "Printing elements in set with auto...\n";for (const auto &elem : set) {std::cout << elem << " ";}std::cout << std::endl;// Overall, auto is a useful C++ keyword that can be used to write code more// efficiently, and to write cleaner and more readable code.// Keep in mind that using auto to iterate through C++ containers is better// in practice, since it produces more readable code. However, if you're not// sure of the types that are being used, it is always okay to revert back// to figuring out the type yourself.// 总的来说,auto 是一个有用的 C++ 关键字,可用于更高效地编写代码,并编写更干净、更易读的代码。// 请记住,在实践中使用 auto 遍历 C++ 容器会更好,因为它会生成更具可读性的代码。// 但是,如果不确定正在使用的类型,则始终可以恢复到自己确定类型。return 0;
}

运行结果

这篇关于【cmu15445c++入门】(7)C++ auto 关键字的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/685737

相关文章

C++类和对象之初始化列表的使用方式

《C++类和对象之初始化列表的使用方式》:本文主要介绍C++类和对象之初始化列表的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C++初始化列表详解:性能优化与正确实践什么是初始化列表?初始化列表的三大核心作用1. 性能优化:避免不必要的赋值操作2. 强

C++迭代器失效的避坑指南

《C++迭代器失效的避坑指南》在C++中,迭代器(iterator)是一种类似指针的对象,用于遍历STL容器(如vector、list、map等),迭代器失效是指在对容器进行某些操作后... 目录1. 什么是迭代器失效?2. 哪些操作会导致迭代器失效?2.1 vector 的插入操作(push_back,

全解析CSS Grid 的 auto-fill 和 auto-fit 内容自适应

《全解析CSSGrid的auto-fill和auto-fit内容自适应》:本文主要介绍了全解析CSSGrid的auto-fill和auto-fit内容自适应的相关资料,详细内容请阅读本文,希望能对你有所帮助... css  Grid 的 auto-fill 和 auto-fit/* 父元素 */.gri

POI从入门到实战轻松完成EasyExcel使用及Excel导入导出功能

《POI从入门到实战轻松完成EasyExcel使用及Excel导入导出功能》ApachePOI是一个流行的Java库,用于处理MicrosoftOffice格式文件,提供丰富API来创建、读取和修改O... 目录前言:Apache POIEasyPoiEasyExcel一、EasyExcel1.1、核心特性

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

C#如何调用C++库

《C#如何调用C++库》:本文主要介绍C#如何调用C++库方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录方法一:使用P/Invoke1. 导出C++函数2. 定义P/Invoke签名3. 调用C++函数方法二:使用C++/CLI作为桥接1. 创建C++/CL

C++如何通过Qt反射机制实现数据类序列化

《C++如何通过Qt反射机制实现数据类序列化》在C++工程中经常需要使用数据类,并对数据类进行存储、打印、调试等操作,所以本文就来聊聊C++如何通过Qt反射机制实现数据类序列化吧... 目录设计预期设计思路代码实现使用方法在 C++ 工程中经常需要使用数据类,并对数据类进行存储、打印、调试等操作。由于数据类

Linux下如何使用C++获取硬件信息

《Linux下如何使用C++获取硬件信息》这篇文章主要为大家详细介绍了如何使用C++实现获取CPU,主板,磁盘,BIOS信息等硬件信息,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录方法获取CPU信息:读取"/proc/cpuinfo"文件获取磁盘信息:读取"/proc/diskstats"文

C++使用printf语句实现进制转换的示例代码

《C++使用printf语句实现进制转换的示例代码》在C语言中,printf函数可以直接实现部分进制转换功能,通过格式说明符(formatspecifier)快速输出不同进制的数值,下面给大家分享C+... 目录一、printf 原生支持的进制转换1. 十进制、八进制、十六进制转换2. 显示进制前缀3. 指

C#中async await异步关键字用法和异步的底层原理全解析

《C#中asyncawait异步关键字用法和异步的底层原理全解析》:本文主要介绍C#中asyncawait异步关键字用法和异步的底层原理全解析,本文给大家介绍的非常详细,对大家的学习或工作具有一... 目录C#异步编程一、异步编程基础二、异步方法的工作原理三、代码示例四、编译后的底层实现五、总结C#异步编程