2

I have the following code:

int main()
{
    int intArr[] = { 1,5,3 };
    //auto f = [](auto a, auto b) {return a < b;};
    //std::sort(intArr, intArr + 2, f);
    std::sort(intArr, intArr + 2);
    for (int& temp : intArr)
        cout << temp << endl;
}

However, the output is unsorted (e.g. the output is 1 5 3). The same result when using std::sort with lambda. What is causing this behavior?

I am using Visual C++ compiler (Visual Studio 2015).

Igor Ševo
  • 5,459
  • 3
  • 35
  • 80
  • 4
    `std::sort(intArr, intArr + 3);` – juanchopanza Nov 16 '15 at 12:35
  • You only sort the first two elements. – Some programmer dude Nov 16 '15 at 12:36
  • http://stackoverflow.com/questions/5897319/how-to-use-stdsort-to-sort-an-array-in-c – juanchopanza Nov 16 '15 at 12:37
  • 2
    Why so many downvotes? I believe this is a decent question. – therainmaker Nov 16 '15 at 12:45
  • 1
    That may not be a fancy question, and neither will make it into the hall of fame nor yield great rep gain for answerers, but it **is** a valid and well-formulated question; thus there's no reason to down-vote it. – decltype_auto Nov 16 '15 at 12:49
  • Just reading documentation for `std::sort` would answer this question. –  Nov 16 '15 at 13:00
  • @Satus : It is a very reasonable mistake to assume that you have to include point till the last element, and not its end as well. And many other non-downvoted (even upvoted) questions on the site can be solved with much less effort than that. All I'm saying is that this question showed enough effort, a well curated example, and enough information. – therainmaker Nov 16 '15 at 14:18
  • @therainmaker It is even more reasonable to read documentation of some library function before you post a question about it. And the fact that "many other non-downvoted (even upvoted) questions on the site can be solved with much less effort than that" is not a justification for not downvoting the questing, but a problem of stackoverflow as a question-answer platform. –  Nov 16 '15 at 14:28

2 Answers2

7

In STL algorithms that take ranges, if you want to provide the whole range you have to give as ending an element one-past-the-end and not the end of the range itself, thus in your case:

std::sort(intArr, intArr + 3);

Or

std::sort(intArr, intArr + sizeof(intArr) / sizeof(int));

Or even better:

std::sort(std::begin(intArr), std::end(intArr));
101010
  • 41,839
  • 11
  • 94
  • 168
  • Surely `sizeof(intArr)/sizeof(intArr[0])`? Which is exactly why the `std::end` version is better; avoids all sorts of common mistakes! – Andrew Nov 16 '15 at 12:57
  • @Andrew Never debug while standing up. Thanx corrected. – 101010 Nov 16 '15 at 12:59
2

You have 3 values in array, but send only 2 (since in STL algorithms second parameter is past-end iterator). Should be

std::sort(intArr, intArr + 3);
ForEveR
  • 55,233
  • 2
  • 119
  • 133