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).
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));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With