C++ learn 问题记录

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值