正在爲我的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);
你試過調試你的程序嗎? – antiguru
是的,我得到的唯一信息是「表達式:向量下標超出範圍」 – Sean
這個表達式將會是一個問題:'v [ii + 1])'因爲'i'在給定範圍內:'for (int ii = 0; ii
lurker