The program takes a file with names and GPAs and sorts them in order of highest GPA to lowest using vectors. I cant seem to find out whats wrong with the code. Everytime i run it it says 'vector subscript out of range'. Can someone please help me?

File:
James 3.9
Margaret 3.5
Charles 1.2
Jennifer 4.0

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
#define MAX 2000

void reverse(vector<string> str,int size);
int getArray(vector<string> str, istream& in);
void bubble(vector<string> str, int size);
void printvector(vector<string> a);

int main ()
{
    char filename [256];
    vector<string> str;
    int size;
	cout << "Please enter the name of the file:" << endl;
    cin.getline(filename, 256);
    ifstream inFile;
    inFile.open(filename);
	size = getArray(str, inFile);
	bubble(str, size);
    reverse(str, size);
    inFile.close();
    return 0;
}


void printvector(vector<string> a)
{
	for(unsigned int i=0;i<a.size();i++)
	{
		cout << a[i]<< " ";
	}
	cout << endl;
}

int getArray(vector<string> str, istream& in)
{
       unsigned int i = 0;
    
       while (i < MAX && in >> str[i])
    {
              i++;
    }
       
      unsigned int size = i;
    return size;
}

void bubble(vector <string> str, int size)
{
       for(unsigned int pass = 0; pass < size - 1; pass++)
    {
              for(unsigned int i = 0; i < size - pass -1; i++)
        {
                     if( str[i] > str[i + 1])
            {   
                           string tmp = str[i];
                           str[i] = str[i + 1];
                           str[i + 1] = tmp;
            }
         }
       }
}

void reverse(vector<string> str,int size)
{
       for (unsigned int j = size + 1; j >= 0; j--)
    {
              cout << str[j] << endl;
    }
}

Recommended Answers

All 3 Replies

Line 43 - Shouldn't you be using insert or push_back to add an item to a vector?

What would it be?
I tried fixing it but it still doesn't work.

while (i < MAX)
    {
			  str.push_back(50);
              i++;
    }

If you had specified a size for the vector in main, what you did could work, but since it starts off with an unspecified size you can't index into it.

string tempstring;
while(i < MAX && in >> tempstring)
{
     str.push_back(tempstring);
     i++;
}

You should also pass the vector in by reference in order to change it within any of the functions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.