这个 c++ 代码在给出分段错误时有什么问题
What is wrong with this c++ code in giving a segmentation fault?
#include<iostream>
#include<iterator>
#include<vector>
#include<algorithm>
using namespace std;
int main (void)
{
int z,foo,t,n,k,i;
cin>>t;
while (t--)
{
vector<int> a;
vector<int> b;
cin>>n>>k;
z = n;
while (z--)
{
cin>>foo;
a.push_back(foo);
}
sort(a.begin(),a.end());
vector<int>::iterator it = a.begin();
vector<int>::iterator bt = a.begin();
while (bt != a.end())
{
bt = bt + (k-1);
foo = *bt - *it;
b.push_back(foo);
it++;
}
sort(b.begin(),b.end());
cout<<b[0]<<"n";
}
return 0;
}
此代码接受测试用例的数量,然后接受两个数字,然后取数字的总数,并对它们进行排序,根据k
取它们的差值并对它们进行排序,在新的向量中复制并对其进行排序并输出一个新元素。
上面的代码给出了一个分段错误。
您在循环的每次迭代中通过k - 1
步骤来移动bt
bt = bt + (k-1);
bt
的初始值为 a.begin()
,循环延续条件为 bt != a.end()
。如果大小为a
(即 n
(不能被k - 1
整除,bt
永远不会等于a.end()
,循环永远不会正确终止。它将bt
推出有效范围。
此时,行为将是未定义的。代码通常会崩溃。
相关文章:
- 警告处理为错误这里有什么问题
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 0-1背包代码中的错误.我的代码中有什么错误
- 是什么导致了Unity 3D中的"错误线程异常"?
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 你能解释一下什么运行时错误是如何解决它的吗?
- 在C++中创建队列 - 什么是 malloc 错误?
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- 没有可行的过载'='错误,可能导致这种情况的原因是什么?
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 这个失败的测试是将零添加到空指针未定义的行为、编译器错误还是其他什么?
- Clang 8 带有静态 constexpr 和数组的链接器错误 - 错误是什么以及如何解决它?
- 我遇到了黑客排名中的问题"TWO STRINGS"的三个测试用例的分段错误。原因是什么?
- 什么会导致LNK2019 VisualStudio中的错误?
- 导致hash_map错误的原因是什么,如何修复它?
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- 我正在尝试学习如何在 c++ 中传递指针,但出现错误:没有用于调用"test"的匹配函数。我做错了什么?
- 当我选择大于 720 的矩阵大小时,程序退出并显示错误代码.可能是什么原因?
- Makefile错误:什么都不做