前言
C++11 增加了很多C++程序员期待已久的for range循环, 使用for range 可以让代码变得更简洁,开发效率更高
使用场景
1 遍历字符串
// string
std::string strTest("Hello World");
// before
for(std::string::iterator iter = strTest.begin(); iter != strTest.end(); iter++)
{
std::cout << *iter << std::endl;
}
// c++ 11
for(auto ch : strTest)
{
std::cout <<ch << std::endl;
}
2 遍历数组
不用知道数组容器的大小,也可方便的遍历数组。
// array
int arr[] = {1,2,3,4};
int arrLen = 4;
// before
for(int loop = 0; loop < arrLen; loop ++)
{
std::cout << arr[loop] << std::endl;
}
// c++11
for(auto loop : arr)
{
std::cout << loop << std::endl;
}
3 遍历vector
// vector
std::vector<std::string> mvec {"I", "like", "china"};
// before
for(int loop = 0; loop < mvec.size(); loop++)
{
std::cout << mvec[loop] << std::endl;
}
// c++11
for(auto it : mvec)
{
std::cout << it << std::endl;
}
4 遍历list
// list
std::list<std::string> mlist {"I", "am", "a", "goodboy"};
// before
for(std::list<std::string>::iterator iter = mlist.begin(); iter != mlist.end(); iter++)
{
std::cout << *iter << std::endl;
}
// c++11
for(auto it: mlist)
{
std::cout << it << std::endl;
}
5 遍历map
// map
std::map<int, std::string> mMap = {{1, "c++"}, {2, "jave"}, {3, "python"}, {4, "go"}};
// before
for(std::map<int, std::string>::iterator iter = mMap.begin(); iter != mMap.end(); iter++)
{
std::cout << iter->first << std::endl;
std::cout << iter->second << std::endl;
}
// c++11
// 遍历map返回的是pair变量,不是迭代器。
for(auto it:mMap)
{
std::cout << it.first << std::endl;
std::cout << it.second << std::endl;
}