I am trying to take an input number, make a vector with that many elements, take in those elements, and then sort the elements by largest to smallest. I believe I am close but I am getting an error :
Exited with return code -6 (SIGABRT).
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 5) >= this->size() (which is 5)
Example: if the input is 5 10 4 39 12 2, the output should be 39,12,10,4,2,
Here is my code, I am thinking that I am getting the error from looping through my function, but I cannot figure out which one and I have tried changing all the loops.
#include <iostream>
#include <vector>
using namespace std;
void SortVector(vector<int>& myVec){
int tempNum;
for (int i = 0; i < myVec.size(); ++i){
if (myVec.at(i) < myVec.at(i+1)){
tempNum = myVec.at(i);
myVec.at(i) = myVec.at(i + 1);
myVec.at(i + 1) = tempNum;
}
}
}
void print(vector<int>& myVec){
for(int i = 0; i < myVec.size(); ++i){
cout << myVec.at(i)<<", ";
}
}
int main() {
int numOfVector;
cin >> numOfVector;
vector<int> myVec(numOfVector);
for(int i = 0; i < numOfVector; ++i){
cin >> myVec.at(i);
}
SortVector(myVec);
print(myVec);
return 0;
}