首頁 > 後端開發 > C++ > 主體

為什麼 std::sort 不為小範圍呼叫我的自訂交換函式?

Barbara Streisand
發布: 2024-10-26 12:32:02
原創
528 人瀏覽過

Why doesn't std::sort call my custom swap function for small ranges?

std::sort 不總是呼叫std::swap

問題:

問題:
<code class="cpp">#include <algorithm>
#include <iostream>
#include <vector>

namespace my_space
{

struct A
{
    double  a;
    double* b;
    bool operator<(const A&amp; rhs) const
    {
        return this->a < rhs.a;
    }
};

void swap(A&amp; lhs, A&amp; rhs)
{
    std::cerr << "My swap.\n";
    std::swap(lhs.a, rhs.a);
    std::swap(lhs.b, rhs.b);
}

}

int main()
{
    const int n = 20;
    std::vector<my_space::A> vec(n);
    for (int i = 0; i < n; ++i) {
        vec[i].a = -i;
    }

    for (int i = 0; i < n; ++i) {
        std::cerr << vec[i].a << " ";
    }
    std::cerr << "\n";
    std::sort(vec.begin(), vec.end());
    for (int i = 0; i < n; ++i) {
        std::cerr << vec[i].a << " ";
    }
    std::cerr << "\n";
}
登入後複製

問題:

問題:

<code class="cpp">typename iterator_traits<_RandomAccessIterator>::value_type
  __val = _GLIBCXX_MOVE(*__i);
_GLIBCXX_MOVE_BACKWARD3(__first, __i, __i + 1);
*__first = _GLIBCXX_MOVE(__val);</code>
登入後複製

在下面的程式碼中,為什麼在較小範圍(n=4)執行std::sort 時未呼叫自訂交換函數,即使在較大範圍(n=20)中呼叫它? 答案:對於小範圍,GCC 的stdlibc(和其他標準庫實現)中的std::sort 實現出於性能原因使用插入排序。插入排序不使用 std::swap 來交換元素。相反,它一次移動整個範圍的值,可能會節省效能。 GCC 插入排序實作中的相關代碼(bits/stl_algo.h:2187,GCC 4.7.2)是:此程式碼將目前位置(__i) 的值移到到臨時存儲,將所有先前的值從__first 向上移動到__i,然後在__first 處重新插入臨時值。透過這樣做,它可以在一次操作中執行 n 次交換,而不必單獨移動 n 個值。

以上是為什麼 std::sort 不為小範圍呼叫我的自訂交換函式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!