C++11 std - auto

倒序输出字符串的C++实现及解析
本文深入探讨了使用C++编程语言倒序输出字符串的方法,并详细解释了两种实现方式的区别与优势,强调了`auto`关键字在简化代码方面的作用。

下面是倒序输出字符串的代码:

#include <stdio.h>
#include <cstdlib>
#include <string>
#include <iostream>
#include <thread>
#include <array>

using namespace std;

int main(int argc, char *argv[])
{
	freopen("temp.txt","w",stdout);
	string str("hello world");
	//C++98的写法
	//for (string::iterator i=str.begin(); it!=str.end(); ++i)

	//C++11的写法
	for(auto i = str.crbegin(); i!=str.crend();i++)
	{
		cout<<*i;
	}
	while(1);
    return EXIT_SUCCESS;
}

输出结果:

dlrow olleh

分析:

line 15 明显比 line 18行简便

结论:

auto 的主要功能就是是代码更加简洁。下面这段话是出自 《The C++ Standard Library Second Edition》

Using auto is especially useful where the type is a pretty long and / or complicated expression.

auto并非属于std命名空间,它是C++11引入的全局关键字。在C++11及后续版本中,auto作为类型指示符,为局部变量类型推导提供了便利,但在全局范围或命名空间中使用可能导致类型不明确或代码难以理解[^1]。 auto的使用细则如下: - **与指针和引用结合使用**:auto可与指针和引用结合,编译器能正确推导类型。 - **同一行定义多个变量**:在同一行用auto定义多个变量时,这些变量的初始类型必须一致,否则编译会报错。 auto存在不能推导的场景: - **不能作为函数的参数**:函数参数需要明确的类型,auto无法在函数调用时进行类型推导。 - **不能直接用来声明数组**:auto无法推导数组类型。 为避免与C++98中的auto混淆,C++11仅保留了其作为类型指示符的用法。auto在实际中常见的优势用法是与C++11提供的新式for循环和lambda表达式等配合使用[^2]。 正确使用auto可显著提高代码的可读性和简洁性,但使用时需遵循一定的限制和最佳实践,要充分考虑使用场景和可能出现的问题[^1]。 示例代码如下: ```cpp #include <iostream> #include <vector> int main() { // auto与指针结合 auto ptr = new int(42); std::cout << *ptr << std::endl; delete ptr; // auto与引用结合 int num = 10; auto& ref = num; ref = 20; std::cout << num << std::endl; // auto与新式for循环配合 std::vector<int> vec = {1, 2, 3, 4, 5}; for (auto element : vec) { std::cout << element << " "; } std::cout << std::endl; // auto与lambda表达式配合 auto add = [](int a, int b) { return a + b; }; std::cout << add(3, 5) << std::endl; return 0; } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值