1. 程式人生 > >C++模板超程式設計----快速排序

C++模板超程式設計----快速排序

## 目錄 - [目錄](#目錄) - [簡介](#簡介) - [實現](#實現) - [資料結構定義](#資料結構定義) - [在陣列前新增一個元素](#在陣列前新增一個元素) - [判斷](#判斷) - [分堆](#分堆) - [合併](#合併) - [快速排序的實現](#快速排序的實現) - [總結](#總結) ## 簡介 上一篇使用C++模板模板實現了一個選擇排序。這一次,更進一步的,實現了一個快速排序演算法。關於快速排序的可以看這一篇文章[快速排序](http://data.biancheng.net/view/117.html) ## 實現 和上一次一樣,我把快速排序演算法分為幾個小的步驟,分別實現,然後聯合在一起,實現演算法。 ### 資料結構定義 和之前類似,不過多定義了一個`head_type`,同時對一些型別進行了改名。 ```C++ // 資料結構定義 template struct mvector; template struct mvector<_head, data...> { constexpr static int head = _head; typedef mvector<_head> head_type; typedef mvector tail_type; constexpr static std::array value = {_head, data...}; }; template struct mvector<_head> { constexpr static int head = _head; typedef mvector<_head> head_type; typedef mvector<> tail_type; constexpr static std::array value = {_head}; }; template<> struct mvector<> { constexpr static int head = -1; typedef mvector<> head_type; typedef mvector<> tail_type; constexpr static std::array value = {}; }; ``` ### 在陣列前新增一個元素 ```C++ // 在陣列前增加一個元素 template struct add_to_list; template struct add_to_list> { typedef mvector result_type; }; ``` ### 判斷 ```C++ // 判斷,輸出一個型別 template struct m_type_if; template struct m_type_if { typedef T result_type; typedef S not_result_type; }; template struct m_type_if { typedef S result_type; typedef T not_result_type; }; ``` ### 分堆 根據第一個元素,將不同的元素分在不同的陣列中 ```C++ // 分堆 template struct m_diff; template struct m_diff<_mid, mvector> { typedef _mid mid; typedef m_diff<_mid, mvector> next_type; typedef typename m_type_if::result_type, typename next_type::right_type>::result_type right_type; typedef typename m_type_if= mid::head, typename add_to_list::result_type, typename next_type::left_type>::result_type left_type; }; template struct m_diff<_mid, mvector<>> { typedef _mid mid; typedef m_diff<_mid, mvector<>> next_type; typedef mvector<> right_type; typedef mvector<> left_type; }; ``` ### 合併 ```C++ // 合併 template struct combine_result; template struct combine_result, mvector, mvector> { typedef mvector result_type; }; ``` ### 快速排序的實現 ```C++ // 快排 template struct QuickSortWork; template struct QuickSortWork> { typedef m_diff::head_type, typename mvector::tail_type> diffed_type; typedef typename QuickSortWork::result_type right_type; typedef typename QuickSortWork::result_type left_type; typedef typename combine_result::head_type, left_type>::result_type result_type; }; template<> struct QuickSortWork> { typedef mvector<> result_type; }; template struct QuickSort { typedef QuickSortWork> work_type; constexpr static std::array result = work_type::result_type::value; }; ``` ## 總結 原始碼:https://gist.github.com/ink19/2dd0c466db4a11611a9b75e78dd25b4e 和之前的感覺類似,不過使用更加順手了。 部落格原文:部落格原文:https://www.cnblogs.com/ink19/p/cpp_template_quick_so