首先,先给出书中所示的利用下标运算符实现划分分数段的程序:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<unsigned> scores(11, 0);
unsigned grade;
while (cin >> grade)
if (grade <= 100)
++scores[grade / 10];
for (auto c : scores)
cout << c << " ";
system("pause");
return 0;
}
题目中要求使用迭代器改写程序并实现完全相同的功能:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<unsigned> scores(11,0);
unsigned grade;
auto it = scores.begin();
while (cin >> grade)
if (grade <= 100)
++*(it + grade / 10);
for (auto a : scores)
cout << a << " ";
system("pause");
return 0;
}