C++11中范围for循环简化容器遍历,语法为for (declaration : container),自动管理迭代器,支持引用避免拷贝,提升代码安全与简洁性。

在C++11中,范围for循环(range-based for loop)提供了一种简洁、安全的方式来遍历容器。它自动处理迭代器的创建和移动,无需手动管理下标或指针。
范围for循环的语法格式如下:
for (declaration : container) {
// 操作元素
}
declaration 是对容器中每个元素的声明,可以使用引用或const引用以避免拷贝。
以下是一些常见用法:
立即学习“C++免费学习笔记(深入)”;
std::vector<int> nums = {1, 2, 3, 4, 5};
for (int n : nums) {
std::cout << n << " ";
}
std::vector<std::string> words = {"hello", "world"};
for (std::string& word : words) {
word += "!"; // 可修改原元素
}
for (const std::string& word : words) {
std::cout << word << std::endl; // 只读访问
}
只要容器定义了 begin() 和 end() 成员函数(或可用的非成员版本),就可以使用范围for循环。包括:
int arr[] = {10, 20, 30};
for (int x : arr) {
std::cout << x << " ";
}
以上就是C++11如何使用范围for循环遍历容器的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号