1. 基于范围(range-based)的 for 循环
#include <iostream>
#include <vector>
using namespace std;
int main() {
double prices[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
for(double i: prices)
cout << i << " ";
cout << endl;
// 要修改数组的元素,则要使用引用变量
double pricess[5];
for(double &i: pricess)
cin >> i;
for(double i: pricess)
cout << i << " ";
cout << endl;
vector<int> nums;
for(int i = 0; i < 6; i++)
nums.push_back(10 + i);
for(int i : nums) {
cout << i << " ";
}
cout << endl;
return 0;
}
2. for_each 语句
for_each 算法中使用了“迭代器”(指针),其内部包含了自增操作的概念,所以不需要写上 ++p 指针,但是对于该循环体得给出其界限范围. 很多地方使用 for_each 语法来使用 STL 遍历容器.
需要包含头文件 #include <algorithm>
严格来说第三个参数的要求是 C++ concepts: FunctionObject,所以传入的参数可以为下列类型之一:
- 1.函数指针/引用;
- 2.含有operator ()成员的类型对象(functor),且std::for_each具有访问该成员的权限;
- 3.lambda.
比如传入“函数名”其实是第一条。另外,传入的对象必须可以以解引用的迭代器为唯一参数调用。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void myPrint(int& elem) {
cout << elem << " ";
}
int main() {
vector<int> nums;
for(int i = 0; i < 6; i++)
nums.push_back(10 + i);
// 1.传入global function name
for_each(nums.begin(), nums.end(), myPrint);
cout << endl;
// 未完待续
return 0;
}