C ++向量下标问题

时间:2016-01-30 00:45:19

标签: c++ vector

我正在创建一个计算任何整数的均值,中位数和范围的应用程序,但我遇到了问题:向量下标超出范围。我已经查看了其他一些有关此事的帖子,但仍无法修复它。

这是我的代码:

#include <iostream>
#include <Algorithm>
#include <Windows.h>
#include <vector>

using namespace std;

int main() {
    //Variables
    int sze;
    int mraw = 0;
    double mean;
    double median;
    double range;
    int fullnum = 0;
    int lastnum = 1;
    vector<int> med;

    cout << "How many numbers do you have?  ";
    cin >> sze;
    int *arr = new int[sze];
    for (int i = 0; i < sze; i++) {
        med.push_back(arr[i]);
    }
    //Getting numbers
    for (int i = 0; i < sze, i++;) {
        system("cls");
        cout << "Enter number #" << i + 1 << ": ";
        cin >> arr[i];
    }

    //Mean

    for (int i = 0; i < sze; i++){
        fullnum += arr[i];
    }
    mean = fullnum / sze;

    //Median

    sort(med.begin(), med.end());
    int mvs = sze;
    while (med.size() >= 2) {
        med.erase(med.begin());
        med.erase(med.begin() + med.size() - 1);
        mvs--;
    }
    if (mvs == 2) {
        mraw = med[1] + med[2];
        median = mraw / 2;
    }
    else {
         median = mvs;
    }

    //Range

    vector<int> rnge;
    for (int i = 0; i < sze; i++) {
        rnge.push_back(arr[i]);
        lastnum++;
    }
    sort(rnge.begin(), rnge.end());
    int bigsmall[2];
    bigsmall[1] = rnge[1];
    bigsmall[2] = rnge[lastnum];
    range = bigsmall[2] - bigsmall[1];

    //Outputs

    cout << "Mean: " << mean << "\nMedian: " << median << "\nRange: " << range;
    system("cls");
    return 0;
}

1 个答案:

答案 0 :(得分:0)

如果lastnum初始化为0,您将拥有off-by-one error

rnge为空时,大概lastnum0。这意味着访问rnge[lastnum]出错,因为rnge为空。

应用归纳参数表明lastnum是元素数量的计数,而不是最后一个元素的索引。因此,rnge[lastnum]总是超出范围。

实际上,您已将lastnum初始化为1,因此您的错误实际上是 off-by-two