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循环”
是不会有
任何问题的,因为这些容器中都定义了相关操作。