一、std::for_each
用于遍历STL容器,定义于头文件 <algorithm>
语法:
|
将函数 fn 应用于[first,last)范围内的每个元素
。
参数:
first,last | 迭代器序列中的初始位置和最终位置。使用的范围是[first,last) ,它包含first和last之间的所有元素,包含first指向的元素,但不包含last指向的元素。 |
fn | 一元函数对象,即参数只能是[first,last) 中的元素。可以是函数指针,可以是可移动构造函数对象。如果有返回值,将会被忽略。 |
此函数的行为等效于:
template <class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function fn)
{
while (first != last)
{
fn(*first);
++first;
}
return fn; // or, since C++11: return move(fn);
}
例:
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
struct Sum
{
Sum() : sum{0} {}
void operator()(int n) { sum += n; }
int sum;
};
void play(int n) //①如果只是调用,参数只需要写int n
{
cout << " " << n;
}
int main()
{
vector<int> nums{3, 4, 2, 8, 15, 267};
auto print = [](const int &n) { cout << " " << n; };
cout << "before:";
for_each(nums.begin(), nums.end(), print);
cout << '\n';
for_each(nums.begin(), nums.end(), [](int &n) { n++; });//②如果要进行写操作,需要引用n,即 int &n
// 对每个数调用 Sum::operator()
Sum s = for_each(nums.begin(), nums.end(), Sum());
cout << "after: ";
for_each(nums.begin(), nums.end(), play);
cout << '\n';
cout << "sum: " << s.sum << '\n';
system("pause");
return 0;
}
/*输出
before: 3 4 2 8 15 267
after: 4 5 3 9 16 268
sum: 305
*/
二、for(auto a:b)
C++11起新特性,for循环的另一种用法,其中a是遍历b的每一个元素。
b可以是数组或者容器
for(auto a:b)效果是利用a遍历并获得b中的每一个值,但是a无法影响到b中的元素。
for(auto &a:b)中加了引用符号,可以对b中的内容进行赋值,即可通过对a赋值来做到b的内容改变。
例:
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
string s = "hello world"; //string可以看成一个容器
for (auto c : s)
cout << c;
cout << endl;
int b[] = {1, 2, 3, 4, 5, 6}; //数组
for (auto &a : b)
a++;
for (auto a : b)
cout << a << " ";
cout << endl;
system("pause");
return 0;
}
/*输出
hello world
2 3 4 5 6 7
*/