获取'向量下标超出范围'错误

时间:2015-11-12 15:21:21

标签: c++ vector max min

处理我的C ++类的作业,我收到了标题中提到的错误。我知道这不是很多,但我认为这可能是我如何调用我的函数的问题。我的代码如下。

主:

#include <iostream>
#include <vector>
#include "VectorHeader.h"
using namespace std;
int main()
{
int items, num, sum, min, max, avg;
vector<int> v;

cout << "How many items would you like in this vector?" << endl;
cin >> items;

/* After the user enters his numbers, the for loop will enter those numbers into the vector */
cout << "Please enter the numbers you would like in the vector." << endl;
for (int ii = 0; ii < items; ii++)
{
    cin >> num;
    v.push_back(num);
}

/* This block prints the vector neatly by checking for when the last number in the vector appears */
cout << "Your vector = <";
for (int ii = 0; ii < v.size(); ++ii)
{
    if (ii < v.size()-1)
        cout << v[ii] << ", ";
    else
        cout << v[ii];
}
cout << ">" << endl;

sum = Sum(v);
min = Min(v);
max = Max(v);
avg = Average(v);

cout << "The sum of your vector = " << sum << endl;
cout << "The min of your vector = " << min << endl;
cout << "The max of your vector = " << max << endl;
cout << "The average of your vector = " << avg << endl;

return 0;
}

功能:

#include <iostream>
#include <vector>
#include "VectorHeader.h"
using namespace std;

int Sum(vector<int> &v)
{
int sum = 0;
for (int ii = 0; ii < v.size(); ii++) // For loop for finding the sum of the       vector
{
    sum += v[ii];
}

return sum;
}

int Min(vector<int> &v)
{
int min;
for (int ii = 0; ii < v.size(); ii++) // Runs through the vector setting the     new min to 'min' each time it finds one
{
    if (v[ii] < v[ii + 1])
        min = v[ii];
}
return min;
}

int Max(vector<int> &v)
{
int max;
for (int ii = 0; ii < v.size(); ii++) // Runs through the vector setting the     new max to 'max' each time it finds one
{
    if (v[ii] > v[ii + 1])
        max = v[ii];
}
return max;
}

int Average(vector<int> &v)
{
int avg, sum = 0;
for (int ii = 0; ii < v.size(); ii++) // For loop for finding the sum of the vector
{
    sum += v[ii];
}
avg = sum / v.size(); // Then divide the sum by the number of vector items to find the average

return avg;
   }

最后,头文件:

#include <iostream>
#include <vector>
using namespace std;

int Sum(vector<int> &v);
int Min(vector<int> &v);
int Max(vector<int> &v);
int Average(vector<int> &v);

2 个答案:

答案 0 :(得分:1)

在Min()和Max()函数中,使用v[ii+1]ii == v.size() - 1;时超出范围。

答案 1 :(得分:1)

罪魁祸首是ii + 1 - 当iiv.size() - 1时,它位于向量之外。

将边界条件更改为v.size() - 1