Eduardo Hashimoto
Eduardo Hashimoto

Reputation: 69

Return vector from a function C++

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;

}

Upvotes: 4

Views: 18702

Answers (2)

Doan
Doan

Reputation: 208

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;
}

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227370

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.

Upvotes: 11

Related Questions