אלוהים אמיתי 2021-05-03 21:22 采纳率: 50%
浏览 76

c++ primer vector 习题3.24报错

3.24 题目:读入一组整数并把他们存入一个vector对象,用迭代器 将每对相邻整数的和输出出来

#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);
    system("pause");
    return 0;
}

当输入元素个数为偶数时,出现如下错误:

程序可以正常输出但是报错can't dereference out of range vector iterator

当把 18行 it !=vInt.cend()-1 改为 it<vInt.cend()-1 后,不论输入 奇数偶数个元素,都可以正常输出并且不报错

  • 写回答

5条回答 默认 最新

  • CSDN专家-Time 2021-05-03 21:25
    关注

    导致越界

    建议用线性表的数组写法 vInt[0]

    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求苍穹外卖环境配置
  • ¥15 代码在keil5里变成了这样怎么办啊,文件图像也变了,
  • ¥20 Ue4.26打包win64bit报错,如何解决?(语言-c++)
  • ¥15 clousx6整点报时指令怎么写
  • ¥30 远程帮我安装软件及库文件
  • ¥15 关于#自动化#的问题:如何通过电脑控制多相机同步拍照或摄影(相机或者摄影模组数量大于60),并将所有采集的照片或视频以一定编码规则存放至规定电脑文件夹内
  • ¥20 深信服vpn-2050这台设备如何配置才能成功联网?
  • ¥15 Arduino的wifi连接,如何关闭低功耗模式?
  • ¥15 Android studio 无法定位adb是什么问题?
  • ¥15 C#连接不上服务器,