c++ - 我在不使用 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;
}
解决方案
您遇到分段错误的事实是您正在尝试访问未启动的内存。
您不能直接扫描输入,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。你可以找出原因。
推荐阅读
- environment-variables - 关于在常规组件/插件之外使用 Nuxt 的 privateRuntimeConfig 变量的问题
- sql - Vertica:如果未找到记录,则返回零
- javascript - CefSharp 运行 JavaScript
- r - 使用与绘图相同的背景颜色扩展 ggplot 的画布
- python - 实际上使用 scikit-learn 从多元多项式回归中检索多项式
- r - 为什么 R 颜色与 Powerpoint 中的吸管工具不一致?
- docker - 如何向 docker 镜像添加反向代理
- java - 服务器返回 HTTP 响应代码:403 用于 URL:https://dl.bintray.com/qameta/generic/io/qameta/allure/allure/2.15.0/allure-2.15.0.zip
- python - 如何为谷歌数据存储使用类似于firestore的嵌套?
- api - Wikipedia API - 如何摆脱 Wikipedia 超链接/垃圾