Reputation: 1096
I wanted to use the sort() in the algorithm library in C++. I could find examples for sorting vectors only, thus I am trying to initialize a vector by an initialized array. When executing I am getting a segmentation fault and couldn't figure out what is wrong here in the code I wrote.
#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;
}
Upvotes: 0
Views: 240
Reputation: 486
The comments explain that you can use sort with an array just fine (if you look at http://en.cppreference.com/w/cpp/algorithm/sort you'll see that sort
takes two arguments that: -RandomIt must meet the requirements of ValueSwappable and RandomAccessIterator.
. Plain pointers fulfill this requirement).
In your example, the segfault happens because you try to dereference a valid but undereferencable
iterator (the iterator returned by 'end()' in: min=*(packets.begin())- *(packets.end());
. Basically it returns an iterator that points to after
the last element of the vector. If you want to get an iterator to the last element, you can use rbegin()
but of course you need to make sure that the vector is not empty first).
You could have seen this quite easily by running your code under a debugger, you'd see that the segmentation fault had nothing to do with the call to sort
Upvotes: 1
Reputation: 33701
*(packets.end())
packets.end()
returns an iterator to the element, following the last element of the vector.
Attempting to derefenrence it causes Undefined Behavior.
Upvotes: 2