【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;
}

运行结果

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/461290.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Ubuntu 22 部署Zabbix 6.4

一、安装及配置postgresql sudo apt-get update sudo apt-get install postgresql postgresql-client 修改配置文件&#xff0c;配置远程访问&#xff1a;&#xff08;PostgreSQL安装路径下的data&#xff0c;也是安装时data的默认路径&#xff09;data目录下的 pg_hba.conf …

CTFshow web(php命令执行 45-49)

基础知识&#xff1a; 1.绕过cat使用&#xff1a; tac more less head tac tail nl od(二进制查看) vi vim sort uniq rev 2.绕过空格用&#xff1a; %09 <> ${IFS} $IFS$ {cat,fl*} %20 注&#xff1a; %09 ##&#xff08;Tab&#xff09; %20 ##&#xff08;spa…

“智能检测,精准把控。温湿度检测系统,为您的生活带来全方位的健康保障。”#非标协议项目【上】

“智能检测&#xff0c;精准把控。温湿度检测系统&#xff0c;为您的生活带来全方位的健康保障。”#非标协议项目【上】 前言预备知识1温湿度检测系统需求2.代码整合2.1找到编程实现LCD1602显示一行工程&#xff0c;打开代码文件&#xff0c;将所需的LCD1602驱动代码拷贝到温湿…

FastDFS 分布式集群搭建详解

文章目录 前言1、整体架构2、安装配置FastDFS集群2.1 配置tracker2.2 配置storage 3、启动集群4、查看集群情况5、nginx配置5.1 配置storage的四台机器的nginx5.2 配置tracker的两台机器的nginx5.3 配置统一入口 前言 阅读本文章之前请先看上一篇单机版FastDFS安装配置详解&am…

【工作学习 day04】 9. uniapp 页面和组件的生命周期

问题描述 uniapp常用的有&#xff1a;页面和组件&#xff0c;并且页面和组件各自有各自的生命周期函数&#xff0c;那么在页面/组件请求数据时&#xff0c;是用created呢&#xff0c;还是用onLoad呢&#xff1f; 先说结论: 组件使用组件的生命周期&#xff0c;页面使用页面的…

机器学习 | 深入集成学习的精髓及实战技巧挑战

目录 xgboost算法简介 泰坦尼克号乘客生存预测(实操) lightGBM算法简介 《绝地求生》玩家排名预测(实操) xgboost算法简介 XGBoost全名叫极端梯度提升树&#xff0c;XGBoost是集成学习方法的王牌&#xff0c;在Kaggle数据挖掘比赛中&#xff0c;大部分获胜者用了XGBoost。…

Netty源码系列 之 ChannelPipeline IO处理回顾 源码

目录 ChannelPipeline【包含AbstractUnsafe.write的源码流程&#xff0c;比之前更加深化了&#xff0c;必看】 ChannelPipeline概念回顾 ChannelPipeline的创建 Inbound(输入Handler)所对应的事件传播 Outbound(输出Handler)所对应的事件传播【包含AbstractUnsafe.write的…

Flink CDC 与 Kafka 集成:Snapshot 还是 Changelog?Upsert Kafka 还是 Kafka?

博主历时三年精心创作的《大数据平台架构与原型实现:数据中台建设实战》一书现已由知名IT图书品牌电子工业出版社博文视点出版发行,点击《重磅推荐:建大数据平台太难了!给我发个工程原型吧!》了解图书详情,京东购书链接:https://item.jd.com/12677623.html,扫描左侧二维…

通过Demo学WPF—数据绑定(二)

准备 今天学习的Demo是Data Binding中的Linq&#xff1a; 创建一个空白解决方案&#xff0c;然后添加现有项目&#xff0c;选择Linq&#xff0c;解决方案如下所示&#xff1a; 查看这个Demo的效果&#xff1a; 开始学习这个Demo xaml部分 查看MainWindow.xaml&#xff1a; …

HiveSQL——条件判断语句嵌套windows子句的应用

注&#xff1a;参考文章&#xff1a; SQL条件判断语句嵌套window子句的应用【易错点】--HiveSql面试题25_sql剁成嵌套判断-CSDN博客文章浏览阅读920次&#xff0c;点赞4次&#xff0c;收藏4次。0 需求分析需求&#xff1a;表如下user_idgood_namegoods_typerk1hadoop1011hive1…

如何在vue中使用拖动排序组件sortablejs

效果图&#xff1a; 1.首先&#xff0c;我们需要在vue项目中安装依赖&#xff1a; npm install -save sortablejs2.创建demo文件>demoTest.vue&#xff0c;直接附上实例代码&#xff1a; <template><div><div id"table-names"><div class&…

RibbonOpenFeign源码(待完善)

Ribbon流程图 OpenFeign流程图