1 .基于范围的for循环
在c++98中,若要访问一个数组中的数据元素,则需采用循环和下标的方式输出数组中的内容。
如:
#include<iostream>
#include<algorithm>
using namespace std;
int main(int argc,char argv)
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//1.采用数组下标的方式
for (auto i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i)
{
if (i % 10 == 0)
cout << endl;
cout << “arr[” << i << “]” << arr[i] << " ";
}
return 0;
}
1.1 C++11新特性 基于范围的for循环
采用c++11新特性中的基于范围for循环,不必去操心数组越界(边界)问题,因此非常的方便,特别是在项目开发中。
语法形式:
for(declaration:expression)
{
statement
}
其中:
expression部分表示一个对象,用于表示一个序列。
declaration部分负责定义一个变量,该变量将被用于访问序列中的基础元素。
每次迭代,declaration部分的变量会被初始化为expression部分的下一个元素值。
示例1:
#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (auto val : arr)
{
cout << val << " ";
}
system("pause");
return 0;
}
示例2:
若迭代器变量的值希望能够在for中被修改,可以采用引用&的方式;
#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (auto &val : arr)
{
if (val == 5)
{
val += 1;
}
cout << val << " ";
}
system("pause");
return 0;
}
示例3:
对于STL标准模板库也同样适用。
#include<iostream>
#include<stdlib.h>
#include<string>
#include<vector>
using namespace std;
int main()
{
vector<int> arr;
arr.push_back(1);
arr.push_back(3);
arr.push_back(5);
arr.push_back(7);
arr.push_back(9);
for (auto &val : arr)
{
cout << val << " ";
}
system("pause");
return 0;
}
示例4.
#include<iostream>
#include<stdlib.h>
#include<string>
#include<map>
using namespace std;
int main()
{
map<int, string> arr;
arr.insert(pair<int, string>(1, "hello"));
arr.insert(pair<int, string>(2, "world."));
for (auto &val : arr)
{
cout << val.first << "," << val.second << endl;
}
system("pause");
return 0;
}
2.基于范围的for循环特点
(1)和普通循环一样,也可以采用continue跳出循环的本次迭代。
(2)用break来终止整个循环
3.基于范围的for循环使用的要求及依赖条件
(1)for循环迭代的范围是可以确定的;如数组的第一个元素和最后一个元素便构成了for选好的迭代范围。
(2)对于用户自定义的类,若类中定义便实现的有begin、end函数,则这个begin、end便是for循环的迭代范围。
(3)基于范围的for循环要求迭代器的对象实现:++ ==等操作符。
(4)对于STL标准模板库中(如:vector,set,list,map,queue,deque,string等)的各种容器使用“基于范围的for循环”是不会有
任何问题的,因为这些容器中都定义了相关操作。
本文详细介绍了C++11中基于范围的for循环的使用方法和特点,包括基本语法、迭代器变量修改、STL容器应用以及循环控制语句的使用。通过多个示例展示了如何更简洁地遍历数组和各种容器。
2566

被折叠的 条评论
为什么被折叠?



