C++ 我在不使用STL的情况下反转向量时出现分段错误
我无法使用下面的代码来反转向量,尽管反转数组可以工作。 请尽早看一下,因为我做不好。 在数组中,我在返回指针函数时使用static,但在这里我无法理解C++ 我在不使用STL的情况下反转向量时出现分段错误,c++,c++11,data-structures,c++17,C++,C++11,Data Structures,C++17,我无法使用下面的代码来反转向量,尽管反转数组可以工作。 请尽早看一下,因为我做不好。 在数组中,我在返回指针函数时使用static,但在这里我无法理解 #include <bits/stdc++.h> using namespace std; vector<int> reversearray(vector<int> a,int n) { int low=0, high=n-1; while(low&
#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;
}
#包括
使用名称空间std;
矢量反转阵列(矢量a,整数n)
{
int低=0,高=n-1;
而(低)>t;
而(t--)
{
cin>>n;
对于(int i=0;i>v[i];
}
ans=反向旋转(v,n);
对于(int i=0;i而言,您遇到分段错误的事实是您试图访问未初始化的内存
您不能直接扫描到v[i]
的输入,因为向量v
的大小最初为0
而是使用push_back()
方法,或将向量初始化或调整大小为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;
}
PS:我建议不要使用bits/stdc++.h和使用名称空间std。你可以找到原因。但是为什么我们不能使用v[I]?请你解释一下它在哪里初始化为0。但是为什么我们需要调整它的大小,因为在数组中我们从来没有这样做。你能解释一下它背后的概念吗。但是它的动态数组,它自己分配内存,也有Iupvoted,但是我需要15个信誉。你能回答这个问题吗?但是它的动态数组,它自己分配内存吗?运行这里的代码是否给出测试用例失败,请根据此更新代码。
#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;
}