I'm writing a program that has two vectors of different class objects. The function I'm having trouble with reads from files into the two vectors and then is supposed to sort those vectors alphabetically using quickSort(). I constructed quickSort() as a template function so it could work for both vectors.
The inputting part of the function works, but if I include the quickSort() calls I get a 'vector subscript out of range' error.
I'm inexperienced enough that I'm not sure if it's a small error in my implementation or if I'm trying to get the program to do something that just plain doesn't make sense.
Probably you have some sort of "fencepost" error, where you are letting l become greater than v.size()-1, or r become less than 0. Step through the code in a debugger and see at exactly which point one of your index variables becomes >= v.size().
Before you try to sort things like attendees, I suggest testing your program out with small int vectors.
// just to help print the vector for you
std::ostream& operator<<(std::ostream& os, const std::vector<int>& vec)
{
os << "{ ";
for (constauto& ele : vec)
{
os << ele << ' ';
}
return os << "}";
}
int main()
{
std::vector<int> vec {1, 3, 5, 3};
quickSort(vec, 0, 3);
std::cout << vec << '\n';
}
Debug your code through this smaller example and you'll be able to see where the code starts to go down an unexpected path.
Your code worked perfectly with the function, so I realized there must be something wrong with what I was passing to the function. It turns out it was a small error! I was passing vector.size() when I needed to be passing vector.size()-1!
Sometimes I get muddled up by size() counting from 1 while the indexes start from 0.