confusion about using std::less and std::greater with std::sort

半腔热情 提交于 2019-12-01 16:54:48

std::sort behaves like that because it's based on the idea of a strict weak ordering, which is (usually) defined in terms of the < operator.

As to your question; it currently seems to be "I wrote a C function that behaves differently to std::sort. Why is it different?". The answer is: because you wrote a different function!

std::sort sorts in ascending order by default. In case you are looking for descending order, here's the trick:

int x[10] = { 1,3,5,7,9,2,4,6,8,10 };
std::vector<int> vec(x, x+10);          // construct std::vector object
std::sort(vec.rbegin(),vec.rend());     // sort it in reverse manner

This way, you explicitly say that std::sort should treat your array as its end is its beginning and vice versa, which results in your array being sorted in descending order. Here's the full example.


And in case you want to use std::less and std::greater, then it could look like this:

int x[10] = { 1,3,5,7,9,2,4,6,8,10 };
std::sort(x, x + 10, std::less<int>());     // for ascending order
std::sort(x, x + 10, std::greater<int>());  // for descending order

Full example with second solution is here.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!