概述
在C++ 20之前,使用范围for循环时,必须预先声明迭代变量。这在绝大部分场景下,显得非常繁琐和冗余。在C++ 20中,可以直接在范围for循环中初始化集合。这一改进极大提升了代码的简洁性和易读性,允许开发者在一个循环头部声明并初始化集合,避免了单独的变量声明步骤。
对于只需要在循环内部使用的临时集合,这个新特性避免了额外的变量声明,使得代码更加紧凑。另外,范围for初始化将集合的初始化与遍历逻辑紧密结合,使得代码逻辑更加直观,减少了因忘记初始化或错误使用外部变量导致的潜在错误。
基本语法
范围for初始化的基本语法比较简单,可参考如下的伪代码。
for (range_declaration : range_expression)
{
// 循环体
}
其中,range_declaration是用于声明每个元素的变量,其类型通常为auto。如果需要修改元素,则为auto&。range_expression是要遍历的范围,必须是一个支持迭代器的类型,比如:数组、vector、list、map等。
使用方法
范围for初始化比较简单,下面我们通过几个示例来加深大家对其的进一步理解。
1、遍历数组。在下面的示例代码中,我们定义了一个整数数组pNumber,并使用范围for循环遍历数组中的每个元素。在循环体中,我们打印出了每个元素的值。
#include <iostream>
using namespace std;
int main()
{
int pNumber[] = {1, 2, 3, 4, 5};
for (auto item : pNumber)
{
cout << item << " ";
}
cout << endl;
return 0;
}
2、遍历vector。在下面的示例代码中,我们首先定义了一个vector<int>类型的容器vctNumber。然后,使用范围for循环和引用auto &遍历容器中的每个元素,将每个元素的值乘以2。最后,我们再次使用范围for循环遍历容器,并打印出修改后的元素值。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vctNumber = {66, 77, 88, 99, 100};
for (auto& item : vctNumber)
{
// 通过引用方式,可修改容器中的元素
item *= 2;
}
for (auto item : vctNumber)
{
cout << item << " ";
}
cout << endl;
return 0;
}
3、遍历字符串。C++ 20增强了对字符串的遍历,可以直接解引用字符,而不需要显式地使用迭代器或索引,具体用法可参考下面的示例代码。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string strText{ "Hello, World" };
for (auto ch : strText)
{
cout << ch;
}
return 0;
}
4、遍历map容器。在下面的示例代码中,我们定义了一个map<string, int>类型的容器mapFruit,并使用范围for循环遍历容器中的每个键值对。由于map的迭代器解引用后得到的是一个pair<const Key, T>类型的对象,我们在循环中声明了一个常量引用const auto& pair来接收这个键值对,并分别打印出键和值。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
map<string, int> mapFruit = {{"Apple", 36}, {"Lemon", 66}, {"Plum", 88}};
for (const auto& pair : mapFruit)
{
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
💡 如果想阅读最新的文章,或者有技术问题需要交流和沟通,可搜索并关注微信公众号“希望睿智”。