C++中降序排序的工作原理?含std::sort与std::greater<int>()解析
std::sort结合std::greater<int>()的降序排序原理 Hey there! Let's break down exactly how that descending sort code works—no jargon overload, promise.
First, let's start with the basics of std::sort:
std::sortis the go-to sorting function in the C++ Standard Library. By default, it sorts elements in ascending order (smallest to largest). Under the hood, it usesstd::less<int>()as its default comparison rule—this just checks ifa < bto decide which element comes first.- The third parameter you're passing (
std::greater<int>()here) is what's called a comparison predicate: a callable object (could be a function, functor, lambda, etc.) that tellsstd::sorthow to judge the relative order of two elements.
Now let's unpack std::greater<int>():
std::greater<int>is a pre-made functor (a class that behaves like a function) from the<functional>header.- It has an overloaded
operator()method. When you create an instance withstd::greater<int>(), calling it with two integersaandbwill returntrueifa > b, andfalseotherwise. In short:std::greater<int>()(a, b)is exactly the same as writinga > b.
Putting it all together, here's how your line of code works step by step:
std::sortstarts looking at the range of elements in yourvector<int>fromnumbers.begin()tonumbers.end().- Every time it needs to compare two elements (say,
aandb), it uses yourstd::greater<int>()predicate. - If
a > breturnstrue,std::sortplacesabeforeb. If it returnsfalse, it adjusts the order sobcomes first (or leaves them as-is if they're already in the right spot). - By following this rule for all pairs, the algorithm ends up arranging your vector from the largest element to the smallest—aka descending order.
As a quick example: if your numbers vector was {3, 1, 4, 1, 5}, after running that sort line, you'd end up with {5, 4, 3, 1, 1}.
One last note: The underlying algorithm of std::sort is typically a hybrid called introsort (it switches between quicksort, heapsort, and insertion sort depending on the data size), but you don't need to worry about that detail. What matters is that it always follows the comparison rule you provide to determine the final order.
内容的提问来源于stack exchange,提问作者Okasha




