I am working on a program that takes in grades from the user and returns the max, min, avg, median, and standard deviation. I keep encountering this error whenever I try to run my code:
File: c:\program files (x86)\microsoft visual studio 12.0\vc\include\vector
Line: 1201
Expression: Vector subscript out of range
Could someone tell me what I'm doing wrong? No matter what I do, I can't seem to fix it. Completely new to coding in C++, so if you could explain in-depth that would be extremely helpful.
This is the block of code it is referring to in the vector file:
#if _ITERATOR_DEBUG_LEVEL == 2
if (size() <= _Pos)
{ // report error
_DEBUG_ERROR("vector subscript out of range");
_SCL_SECURE_OUT_OF_RANGE;
}
Specifically pointing to this line:
_DEBUG_ERROR("vector subscript out of range");
My code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void enterGrades()
{
int count = 0;//initialize count
int grade;//initialize grade variable
int maxGrade = 0;
vector<int> gradeList;//initialize vector
vector<int>::iterator gradeListIt;//initialize iterator
do {
cout << "Enter grades [0 to exit]: ";//enter grades
cin >> grade;//user input
count += 1;//for each grade, increase count
gradeList.push_back(grade);//append grades to vector
} while (grade != 0);
};
int maxNum(vector<int> gradeList)
{
int largest = gradeList[0];//initialize largest number
int length = gradeList.size();
gradeList.resize(length);
for (int value = 0; value < length; value++)//traverse vector
{
if (gradeList[value] > largest)//if current value > largest
largest = gradeList[value];//set largest to that value
}
return largest;//return largest
};
int minNum(vector<int> gradeList)
{
int smallest = gradeList[0];
int length = gradeList.size();
gradeList.resize(length);
for (int value = 0; value < length; value++)
{
if (gradeList[value] < smallest)
smallest = gradeList[value];
}
return smallest;
};
int avgNum(vector<int> gradeList)
{
int total = 0;
int length = gradeList.size();
gradeList.resize(length);
for (int value = 0; value < length; value++)
{
total += value;
}
return total / length;
};
//int stdDev (vector<int>& gradeList)
//{
// int variance = 0;
// int avg = avgNum(vector<int>& gradeList);
// int length = gradeList.size();
// for(int value = 1; value < length; value++)
// {
// variance = variance + pow(value - avg, 2);
// }
// variance = pow(variance / length, 0.5);
// return variance;
//
//};
int main()
{
vector<int> gradeList;//initialize vector
vector<int>::iterator gradeListIt;//initialize iterator
enterGrades();//
cout << "Maximum grade is: " << maxNum(gradeList) << endl;
cout << "Minimum grade is: " << minNum(gradeList) << endl;
cout << "Average grade is: " << avgNum(gradeList) << endl;
}
Also, in my main function; can I call other functions like I did in my output statements?