The meaning of C++ sort() function cmp

Header file: #include <algorithm>
  std::sort(first,last,cmp);

The range used is [first,last)

省略 cmp,使用 sort(first,last), 则默认从 小到大排序。
使用 sort(first,last, greater<T>() ), 则 从 大到小排序。
如果是结构体或者自定义排序规则,则需要自定义cmp 函数。
相等最好返回 false

The meaning of the cmp function: If the return value is True, it means that the sequence (X, Y) should be placed before Y.

bool cmp(int &x,int &y){ 
  return x>y;//意味着x>y的时候,把x放到y前,按大到小排序。 
}

Note : The comparison of the cmp function must be sorted in strict weak order, that is, strictly defined <, a and b comparison, if a==b, must return false, otherwise an exception will be triggered.
for example:

bool cmp(const T &t1, const T &t2)
{
	if (t1.time <= t2.time)
		return true;
	else
		return false;
}

Writing "<=" in the comparison will trigger an exception and should be changed to:

bool cmp(const T &t1, const T &t2)
{
	if (t1.time < t2.time)
		return true;
	else
		return false;
}

おすすめ

転載: blog.csdn.net/yeeanna/article/details/126910403