#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vInt;
int iVal;
cout << "请输入一组数字:" << endl;
while (cin >> iVal)
vInt.push_back(iVal);
if (vInt.cbegin() == vInt.cend()) {
cout << "没有任何元素" << endl;
return -1;
}
cout << "相邻两项的和依次是:" << endl;
// 利用 auto 推断 it 的类型
for (auto it = vInt.cbegin(); it != vInt.cend() - 1; it++) {
// 求相邻两项的和
cout << (*it + *(++it)) << " ";
// 每行输出 5 个数字
if ((it - vInt.cbegin() + 1) % 10 == 0)
cout << endl;
}
// 如果元素个数是奇数,单独处理最后一个元素
if (vInt.size() % 2 != 0)
cout << *(vInt.cend() - 1);
return 0;
}
// 运行结果
请输入一组数字:
1 2 3 4 5 6 7 8 9 10 11 12 13 q
相邻两项的和依次是:
3 7 11 15 19
23 13
Process finished with exit code 0
问题1
以上代码调试时,输入q才会继续执行,为什么呢?q的作用和含义是什么呢?
问题2
// 每行输出 5 个数字 if ((it - vInt.cbegin() + 1) % 10 == 0) cout << endl;
上段代码中这一句就可以每行输出5个数字,为什么?没理解,而另一段代码则是%5
两者之间的区别是什么?
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vInt;
int iVal;
cout << "请输入一组数字:" << endl;
while (cin >> iVal)
vInt.push_back(iVal);
if (vInt.cbegin() == vInt.cend()) {
cout << "没有任何元素" << endl;
return -1;
}
cout << "首尾两项的和依次是:" << endl;
auto beg = vInt.begin();
auto end = vInt.end();
// 利用 auto 推断 it 的类型
for (auto it = beg; it != beg + (end - beg) / 2; it++) {
// 求首尾两项的和
cout << (*it + *(beg + (end - it) - 1)) << " ";
// 每行输出 5 个数字
if ((it - beg + 1) % 5 == 0)
cout << endl;
}
// 如果元素个数是奇数,单独处理最后一个元素
if (vInt.size() % 2 != 0)
cout << *(beg + (end - beg) / 2);
return 0;
}
问题三
如下程序中
// 利用迭代器遍历 vUS 的元素并逐个输出 for (; it != vUS.end(); it++) { cout << *it << " ";
for (;这个分号的作用是什么,是不是可以不要
include <iostream>
#include <vector>
using namespace std;
int main() {
// 该 vector 对象记录各分数段的人数,初始值为 0
vector<unsigned> vUS(11);
auto it = vUS.begin();
int iVal;
cout << "请输入一组成绩(0 ~ 100):" << endl;
while (cin >> iVal)
if (iVal < 101) // 成绩应在合理范围之内
++*(it + iVal / 10); // 利用迭代器定位到对应的元素,加 1
cout << "您总计输入了 " << vUS.size() << " 个成绩" << endl;
cout << "各分数段的人数分布是(成绩从低到高):" << endl;
// 利用迭代器遍历 vUS 的元素并逐个输出
for (; it != vUS.end(); it++) {
cout << *it << " ";
}
cout << endl;
return 0;
}
// 运行结果
请输入一组成绩(0 ~ 100):
42 65 95 100 39 67 95 76 88 76 83 92 76 93 q
您总计输入了 11 个成绩
各分数段的人数分布是(成绩从低到高):
0 0 0 1 1 0 2 3 2 4 1
Process finished with exit code 0