我想在C ++中的算法库中使用 sort()。我可以找到仅排序向量的示例,因此我尝试通过初始化数组初始化向量。执行时我遇到了分段错误,无法弄清楚我写的代码中有什么问题。
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n,k,packet[1000],min=0;
scanf("%d",&n);
scanf("%d",&k);
for (int i = 0; i < n; ++i)
{
scanf("%d",&packet[i]);
cout<<i<<endl;
}
cout<<"debug";
vector<int> packets(packet,packet+n);
vector<int>::iterator start,stop;
sort(packets.begin(),packets.begin()+n);
min=*(packets.begin())- *(packets.end());
cout<<min;
for (vector<int>::iterator it=packets.begin(); it!=packets.end()-k; ++it)
{
printf("%d ",*it );
if((*(it+k) - *it)<min)
{
start=it;
stop=it+k;
}
}
printf("%d\n",*stop- *start );
return 0;
}
答案 0 :(得分:2)
*(packets.end())
packets.end()
在向量的最后一个元素后面返回元素的迭代器。
尝试解除它会导致未定义的行为。
答案 1 :(得分:1)
注释说明你可以使用数组排序就好了(如果你看{4}},你会看到sort
有两个参数:-RandomIt must meet the requirements of ValueSwappable and RandomAccessIterator.
。普通指针满足这个要求)。
在您的示例中,发生了段错误,因为您尝试取消引用valid but undereferencable
迭代器(由min=*(packets.begin())- *(packets.end());
中的'end()'返回的迭代器。基本上它返回指向{{的迭代器1}}向量的最后一个元素。如果你想得到最后一个元素的迭代器,你可以使用after
,但当然你需要确保向量不为空第一)。
您可以通过在调试器下运行代码轻松地看到这一点,您会发现分段错误与调用rbegin()