You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

C++中降序排序的工作原理?含std::sort与std::greater<int>()解析

理解C++中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::sort is 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 uses std::less<int>() as its default comparison rule—this just checks if a < b to 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 tells std::sort how 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 with std::greater<int>(), calling it with two integers a and b will return true if a > b, and false otherwise. In short: std::greater<int>()(a, b) is exactly the same as writing a > b.

Putting it all together, here's how your line of code works step by step:

  1. std::sort starts looking at the range of elements in your vector<int> from numbers.begin() to numbers.end().
  2. Every time it needs to compare two elements (say, a and b), it uses your std::greater<int>() predicate.
  3. If a > b returns true, std::sort places a before b. If it returns false, it adjusts the order so b comes first (or leaves them as-is if they're already in the right spot).
  4. 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

火山引擎 最新活动