<p>摘要:<a style="color:#f60; text-decoration:underline;" target="_blank">c++</a>++ sort 函數用于對容器元素進行排序。默認情況下,它使用 字符串數組進行排序。</p>
<p><img src="https://img.php.cn/upload/article/000/000/164/171205434266801.jpg" alt="C++sort函數詳解與示例演示"></p>
<p><strong>C++ 排序函數詳解與示例演示</strong></p>
<p><strong>sort 函數概述</strong></p>
<p>sort 函數是 C++ 標準模板庫 (STL) 中一個強大的函數,用于對容器元素進行排序。它根據指定的比較規則將容器中的元素<a style="color:#f60; text-decoration:underline;" target="_blank">排列</a>成升序或降序。</p>
<p>函數聲明如下:</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:cpp;toolbar:false;'>template<typename Iter>
void sort(Iter first, Iter last);</pre><div class="contentsignin">登錄后復制</div></div><p>其中:</p><ul><li><strong>Iter</strong>:指向容器元素的迭代器類型,可以在容器中移動和訪問元素。</li><li><strong>first</strong>:容器開始迭代器,指定要排序元素的范圍的第一個元素。</li><li><strong>last</strong>:容器結束迭代器,指定要排序元素的范圍的最后一個元素之后的元素。</li></ul><p><strong>自定義比較規則</strong></p><p>默認情況下,sort 函數使用 <code><</code> 運算符進行比較,這意味著它將容器元素按升序排列。如果您希望根據不同的規則排序,可以提供一個自定義比較函數:</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:cpp;toolbar:false;'>bool compare(const Type1& a, const Type2& b)
{
// 自定義比較規則
}
// 在 sort 函數中使用自定義比較函數
sort(first, last, compare);</pre><div class="contentsignin">登錄后復制</div></div><p><strong>實戰案例</strong></p><p><strong>示例 1:對整數數組排序</strong></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:cpp;toolbar:false;'>#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int arr[] = {5, 2, 7, 1, 3};
int len = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + len);
cout << "排序后的數組:";
for (int i = 0; i < len; i++)
{
cout << " " << arr[i];
}
cout << endl;
return 0;
}</pre><div class="contentsignin">登錄后復制</div></div><p>輸出:</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>排序后的數組: 1 2 3 5 7</pre><div class="contentsignin">登錄后復制</div></div><p><strong>示例 2:對字符串數組排序</strong></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:cpp;toolbar:false;'>#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string arr[] = {"apple", "orange", "banana", "kiwi", "mango"};
int len = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + len);
cout << "排序后的數組:";
for (int i = 0; i < len; i++)
{
cout << " " << arr[i];
}
cout << endl;
return 0;
}</pre><div class="contentsignin">登錄后復制</div></div><p>輸出:</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>排序后的數組: apple banana kiwi mango orange</pre><div class="contentsignin">登錄后復制</div></div>
以上就是C++sort函數詳解與示例演示的詳細內容,更多請關注愛掏網 - it200.com其它相關文章!
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。