这个 c++ 代码在给出分段错误时有什么问题

What is wrong with this c++ code in giving a segmentation fault?

本文关键字:错误 什么 问题 分段 c++ 代码 这个      更新时间:2023-10-16
#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推出有效范围。

此时,行为将是未定义的。代码通常会崩溃。

相关文章: