首页 > 解决方案 > 我在不使用 STL 的情况下反转向量时遇到分段错误

问题描述

尽管反转数组有效,但我无法使用下面的代码来反转向量。请尽早查看,因为我无法正确执行。在数组中,我在返回并返回指针函数时使用静态,但在这里我无法弄清楚。

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

标签: c++c++11data-structuresc++17

解决方案


您遇到分段错误的事实是您正在尝试访问未启动的内存。

您不能直接扫描输入,v[i]因为向量的大小v最初为 0。

而是使用push_back()方法或将向量初始化或调整为 size n

看看下面的实现:

#include <iostream>
#include <vector>

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

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

    return a;


}

int main() {

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

        for(int i=0;i<n;i++){
            int x;
            std::cin>>x;
            v.push_back(x);
        }

        ans=reversearray(v,n);
        for(int i=0;i<n;i++)
            std::cout<<ans[i]<<" ";

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

        std::cout<<"\n";

        v.clear();
    }
    return 0;
}

GFG 判决:

在此处输入图像描述

如果你想使用v[i]

#include <iostream>
#include <vector>

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

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

    return a;


}

int main() {

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

        v.resize(n);

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

        ans=reversearray(v,n);
        for(int i=0;i<n;i++)
            std::cout<<ans[i]<<" ";

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

        std::cout<<"\n";
    }
    return 0;
}

在此处输入图像描述

PS:我建议不要使用bits/stdc++.h使用命名空间 std。你可以找出原因。


推荐阅读