The problem is that end() isn't what you think it is; I think it's a sentinel node, but in any event, it's not a valid data element. You can replace it with:
sort(a1.begin(), a1.begin() + size - 1);
I'm looking into a better way to do it, without needing to be given the size of the array.
mzimmers
Junior Poster in Training
81 posts since Oct 2011
Reputation Points: 10
Solved Threads: 8
Well, I'm out of ideas. I've created two sorts that look identical to me. One works, the other hangs. Someone smarter than I am is going to have to explain this one.
#include <vector>
#include <algorithm>
using namespace std;
void STLSort(int data[],int size)
{
vector<int> a1;
vector<int>::iterator last;
a1.reserve(size);
for(int i = 0; i < size; i++)
a1[i] = data [i];
last = a1.begin() + a1.size() - 1;
sort(a1.begin(), a1.begin() + size - 1); // works
sort(a1.begin(), last); // hangs
for(int i = 0; i < size; i++)
data[i] = a1[i];
}
int main ()
{
int myArray[10] = { 9,8,7,6,5,4,3,2,1,0 };
int size = 10;
STLSort(myArray, size);
return 0;
}
mzimmers
Junior Poster in Training
81 posts since Oct 2011
Reputation Points: 10
Solved Threads: 8
stereomatching -
Thanks for the correction. Interesting about the sort accepting a1.end; from this page:
http://www.cplusplus.com/reference/stl/vector/end/
I'd have thought that it would fail, since the 2nd parameter of sort is supposed to be the last element to sort (which is not the same as the end of a vector). But...it works.
mzimmers
Junior Poster in Training
81 posts since Oct 2011
Reputation Points: 10
Solved Threads: 8
Everything you say makes sense. I just found it odd that an algorithm that needs to be told the start and the end of the data (like sort) would expect the end to be beyond the final valid element. But, your position is supported by the results of the program, so I'm inclined to believe you're right.
mzimmers
Junior Poster in Training
81 posts since Oct 2011
Reputation Points: 10
Solved Threads: 8
Arkoenig:
Thanks for the explanation; that does make good sense. Regarding my comment above, that was based on a premise that I now know to be incorrect, namely, that the sort() expected the second argument to be the logical end of the vector, not the "real" end.
Clearly, I didn't add much to this discussion; I'll be more careful in the future.
mzimmers
Junior Poster in Training
81 posts since Oct 2011
Reputation Points: 10
Solved Threads: 8