Below the C++ code is supposed to reverse the vector.
#include <bits/stdc++.h>
using namespace std;
vector<int> reverseArray(vector<int> a){
vector<int> b;
for (int i=0;i<a.size();i++){
b.at(i) = a.at(a.size()-i-1);
}
return b;
}
int main(){
int input;
vector<int> arr;
// read vector
while(cin >> input){
arr.push_back(input);
}
// print vector
for (int i=0;i<arr.size();i++){
cout << arr.at(i) << " ";
}
cout << endl <<"Reversed vector is:- ";
vector<int> r_arr = reverseArray(arr);
// print reversed vector
for (int i=0;i<r_arr.size();i++){
cout << arr.at(i) << " ";
}
}
However, an error is being thrown as follows:-
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)
Aborted (core dumped)
I checked that a.size()-i-1 is varying from 5 to 0 for a.size() = 6. Why is the code not working then? Where is the problem?
Please help, I'm learning C++ STL.