Fate Fate - 17 days ago 5x
C++ Question

Why am I getting std::out_of_range error?

I'm trying to make a function that reorders the elements of a vector if it is not in ascending order. I wrote this but when I compile it I get:

terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check

Could someone tell me what is wrong with my function? Thanks.

void reorder(vector<double>& orderA)
for (unsigned int i = 0; i < orderAngle.size(); ++i)
temp = orderA.at(i);
orderA.at(i) = orderA.at(i+1);
orderA.at(i+1) = temp;



1- As mentioned in the comments by Olzhas, your code will go out of range when i becomes equal to orderAngle.size(), so you need to change your for loop to:

for(unsigned int i = 0; i < orderAngle.size() - 1; ++i)

2- Your algorithm doesn't achieve what you want to achieve.

3- Do you really need to write your own algorithm to sort a vector of doubles? How about using something like the following code:

sort(vec.begin(), vec.end(), [](double x, double y) {

   return (x < y);