2

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?

coleworld
  • 35
  • 1
  • 7
  • You are using lots of different `vector`s. The one you read into is not the same one you then check for `min`/`max`/`avg`. There are lots of issues here, too many to deal with in this question. Suggest you pick up a [good book](http://stackoverflow.com/q/388242/1171191). – BoBTFish Apr 08 '15 at 08:59
  • I remember this error (from when I was learning to work with iterators). Then I looked over your code and saw many more issues than this error. Either way, this error occurs when you have iterators for a vector, but they are not set to any valid position within the vector (they are "out of range" - for that particular vector). – utnapistim Apr 08 '15 at 09:13
  • Other issues with your code: you instantiate iterators without setting them to a position, and _without using them in the code_ (you may as well remove the declarations); you pass vectors by value, when you should pass them by reference or const reference; you append the zero grade to the vector (this will screw up the min and avg. grades); from your comments, you confuse variable declaration with initialization. – utnapistim Apr 08 '15 at 09:14
  • Could not find the out of range, but I have some remarks: Why do you resize the vectors (to their current size)? Dont do that. You are calling the index "value". I find this quite confusing. `value = array[index]` looks more naturally to me. You found the line, where the error is reported. However, you are digging a bit too deep. You have to find out which line in your code causes the problem. You are declaring some iterators, but (in contrast to the comments in the code) you do not initialize them (and you also do not use them at all). – 463035818_is_not_an_ai Apr 08 '15 at 09:26
  • ...Last but not least, there is no need to write your own functions to get the min/max/average but these are one-liners if you use stl algorithms (e.g. look for std::max_element). – 463035818_is_not_an_ai Apr 08 '15 at 09:26
  • @utnapistim Thank you for the response. I honestly have minimum exposure to C++ (only my second day working with it). Was working with python a few days ago and now my class is transitioning into C++. So sorrry for all the errors, all I've been given by my teacher was a link to a bunch of tutorials so I've been trying to teach myself. Would it be better to use an if-else statement instead of the do-while loop I have in enterGrades()? – coleworld Apr 08 '15 at 09:33
  • @tobi303 I see what you're saying. I resized the vectors due to an error that occurred beforehand and the only solution I found online was that, but I can see now that it is redundant. And also, it was a part of the assignment to write our own functions for min/max/avg. – coleworld Apr 08 '15 at 09:39
  • Even though this is an assignment and you were asked to write your own functions I would advise you to take a look at the stl algorithms. I do not understand why students so often get assignments were they are told not to use them. One should use them whenever applicable and you miss an essential part of C++ when you do not know about them. Actually I would solve such an assignment by writing my own function but inside this function I would do nothing else than calling e.g. std::max_element. And then the teacher would have a hard time to explain me why this is not a valid solution. – 463035818_is_not_an_ai Apr 08 '15 at 11:26

1 Answers1

1

Giving things the same name doesn't make them the same thing.

After enterGrades returns, the vector named "gradeList" in main is still empty.
When you try access the first element of an empty vector, you get an error.

Your main should look like this:

int main()
{
    std::vector<int> gradeList = enterGrades();
    cout << "Maximum grade is: " << maxNum(gradeList) << endl;
    cout << "Minimum grade is: " << minNum(gradeList) << endl;
    cout << "Average grade is: " << avgNum(gradeList) << endl;
}

Changing the implementation of enterGrades to fit is left as an exercise.

Also, this thing that you keep doing:

int length = gradeList.size();
gradeList.resize(length);

doesn't make sense, as it's resizing a vector to the size it already had.
Remove it.

You're also repeatedly declaring an iterator for no reason at all.

You also probably want to review what average you're supposed to calculate, as you're calculating the average index in a vector, not the average value.
And watch out for those integer divisions.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82