mardi 21 avril 2020

I am getting Segmentation fault while reversing vectors without using STL

I am unable to use below code to reverse a vector although reversing array works. Please look at it at the earliest as i am unable to do it properly. In arrays i use static while returning and return a pointer function but here i am not able to figure out.

#include <bits/stdc++.h>
    using namespace std;


    vector<int> reversearray(vector<int> a,int n)
    {
        int low=0, high=n-1;

        while(low<high)
        {
            swap(a[low],a[high]);
            low++;
            high--;
        }

        return a;


    }
    int main() {

        int t,n;
        vector<int> v,ans;
        cin>>t;
        while(t--)
        {
            cin>>n;

            for(int i=0;i<n;i++){
                cin>>v[i];
            }

            ans=reversearray(v,n);
            for(int i=0;i<n;i++)
                cout<<ans[i]<<" ";
            //Simple solution would be to iterate in reverse order
            /*for(int i=n-1;i>=0;i--){
                cout<<v[i]<<" ";
            }*/
           cout<<"\n";
        }
        return 0;
    }

Aucun commentaire:

Enregistrer un commentaire