Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple std::sort not working

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).

like image 877
Igor Ševo Avatar asked Jul 25 '26 21:07

Igor Ševo


2 Answers

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));
like image 109
101010 Avatar answered Jul 27 '26 11:07

101010


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);
like image 20
ForEveR Avatar answered Jul 27 '26 11:07

ForEveR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!