欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

C++ 11 新特性:auto、decltype 与范围 for

时间:2026年08月12日 04:46:50 浏览:0

auto 类型推导


auto 让编译器自动推导变量类型,减少冗余代码。


#include <vector>
#include <map>

std::vector<int> vec = {1, 2, 3};
// 旧写法:std::vector<int>::iterator it = vec.begin();
auto it = vec.begin(); // 简洁明了

// 推导复杂类型
std::map<std::string, std::vector<int>> data;
auto ret = data.find("key");

decltype 声明类型


decltype 获取表达式的类型,用于变量声明或函数返回值。


int x = 10;
const int& y = x;
decltype(y) z = x; // z 是 const int& 类型

// 结合 trailing return type
template<typename T, typename U>
auto add(T a, U b) -> decltype(a + b) {
return a + b;
}

范围 for 循环


std::vector<int> nums = {1, 2, 3, 4};
for (int n : nums) {
std::cout << n << std::endl;
}

// 引用修改
for (int& n : nums) {
n *= 2;
}

// const 引用(避免拷贝)
for (const auto& item : large_vector) {
// do something
}

这些特性让 C++ 代码更现代、更安全、更易读。