I am trying to return a vector with the values in the reverse order (e.g, I enter a vector with 0,1,2,3,4 and the function return a vector with 4,3,2,1,0).
The compiler says: Segmentation fault.
In my tests I observed that probably my problem is in the assignment new2 = ret_vec(numbers);, but I don't know what is going on.
#include <string>
#include <iostream>
#include <vector>
using namespace std;
vector<int> ret_vec(vector<int>n){
vector <int> n2;
for (int i = 0; i< n.size(); ++i){
n2[i] = n[i];
}
return n2;
}
void initializer(int s, vector<int>& n){
for (int i = 0; i< s; ++i){
n.push_back(i);
}
}
void print_vector(vector<int> n){
for (int i = 0; i<n.size(); ++i){
cout << n[i] << " ";
}
}
int main () {
vector <int> numbers;
int size;
cin >> size;
initializer(size,numbers);
vector <int> new2(numbers.size());
cout << "Old ";
print_vector(numbers);
new2 = ret_vec(numbers);
cout << "New ";
print_vector(new2);
return 0;
}
ret_vectakes a copy of a vector, attempts to copy the copy the long way (and doesn't do that right), and returns the copy of the copy.