【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

相关文章

从入门到精通MySQL联合查询

《从入门到精通MySQL联合查询》:本文主要介绍从入门到精通MySQL联合查询,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下... 目录摘要1. 多表联合查询时mysql内部原理2. 内连接3. 外连接4. 自连接5. 子查询6. 合并查询7. 插入查询结果摘要前面我们学习了数据库设计时要满

从入门到精通C++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

c++中的set容器介绍及操作大全

《c++中的set容器介绍及操作大全》:本文主要介绍c++中的set容器介绍及操作大全,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录​​一、核心特性​​️ ​​二、基本操作​​​​1. 初始化与赋值​​​​2. 增删查操作​​​​3. 遍历方

解析C++11 static_assert及与Boost库的关联从入门到精通

《解析C++11static_assert及与Boost库的关联从入门到精通》static_assert是C++中强大的编译时验证工具,它能够在编译阶段拦截不符合预期的类型或值,增强代码的健壮性,通... 目录一、背景知识:传统断言方法的局限性1.1 assert宏1.2 #error指令1.3 第三方解决

C++11委托构造函数和继承构造函数的实现

《C++11委托构造函数和继承构造函数的实现》C++引入了委托构造函数和继承构造函数这两个重要的特性,本文主要介绍了C++11委托构造函数和继承构造函数的实现,具有一定的参考价值,感兴趣的可以了解一下... 目录引言一、委托构造函数1.1 委托构造函数的定义与作用1.2 委托构造函数的语法1.3 委托构造函

C++11作用域枚举(Scoped Enums)的实现示例

《C++11作用域枚举(ScopedEnums)的实现示例》枚举类型是一种非常实用的工具,C++11标准引入了作用域枚举,也称为强类型枚举,本文主要介绍了C++11作用域枚举(ScopedEnums... 目录一、引言二、传统枚举类型的局限性2.1 命名空间污染2.2 整型提升问题2.3 类型转换问题三、C

C++链表的虚拟头节点实现细节及注意事项

《C++链表的虚拟头节点实现细节及注意事项》虚拟头节点是链表操作中极为实用的设计技巧,它通过在链表真实头部前添加一个特殊节点,有效简化边界条件处理,:本文主要介绍C++链表的虚拟头节点实现细节及注... 目录C++链表虚拟头节点(Dummy Head)一、虚拟头节点的本质与核心作用1. 定义2. 核心价值二

C++ 检测文件大小和文件传输的方法示例详解

《C++检测文件大小和文件传输的方法示例详解》文章介绍了在C/C++中获取文件大小的三种方法,推荐使用stat()函数,并详细说明了如何设计一次性发送压缩包的结构体及传输流程,包含CRC校验和自动解... 目录检测文件的大小✅ 方法一:使用 stat() 函数(推荐)✅ 用法示例:✅ 方法二:使用 fsee