4

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;

}
1
  • 3
    ret_vec takes 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. Commented May 13, 2015 at 21:25

2 Answers 2

11

I am trying to return a vector with the values in the reverse order

The simplest approach would be to use C++:

vector<int> reverse_vec(const vector<int>& n)
{
  vector<int> ret(n.rbegin(), n.rend());
  return ret;
}

Here, reverse iterators are used to construct a vector with the contents of the input vector reversed. Alternatively, if you want to reverse a vector in place, use std::reverse:

vector<int> v = ....
std::reverse(v.begin(), v.end()); // v is now reversed

As for problems with your code, an obvious one is that you are accessing a vector out of bounds here:

vector <int> n2; // empty vector

for (int i = 0; i< n.size(); ++i){
    n2[i] = n[i]; // oops! n2 accessed out of bounds!
}

The fix is not to use this code at all and go for the simple option.

Sign up to request clarification or add additional context in comments.

Comments

1

In the following function

vector<int> ret_vec(vector<int>n){
    vector <int> n2;

    for (int i = 0; i< n.size(); ++i){
        n2[i] = n[i];
    }

    return n2;
}

You are just copy the content of the parameter vector. (I thing you forgot a space between the parameter and the typ of it)

You can revers the order like this way, too (its reverse it "by hand"):

vector<int> ret_vec(vector<int> n){
    vector <int> n2;

    for(int i=n1.size()-1; i<=0; --i) 
    { 
        n2.push_back(n1[i]);
    }

    return n2;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.