`std::list<>::sort()` - ΪʲôͻȻÇл»µ½×ÔÉ϶øϵIJßÂÔ?

ʱ¼ä£º2023-01-21
±¾ÎĽéÉÜÁË`std::list<>::sort()` - ΪʲôͻȻÇл»µ½×ÔÉ϶øϵIJßÂÔ?µÄ´¦Àí·½·¨£¬¶Ô´ó¼Ò½â¾öÎÊÌâ¾ßÓÐÒ»¶¨µÄ²Î¿¼¼ÛÖµ£¬ÐèÒªµÄÅóÓÑÃÇÏÂÃæËæןú°æÍøµÄС±àÀ´Ò»Æðѧϰ°É£¡

ÎÊÌâÃèÊö

ÎҼǵôÓÒ»¿ªÊ¼£¬ÊµÏÖ std::list<>::sort() µÄ×îÁ÷Ðз½·¨ÊÇÔÚ ×Ô϶øÉϵÄʱÉÐ(Áí¼ûÊÇʲôÈà gcc std::list ÅÅÐòʵÏÖÈç´ËÖ®¿ì?).

ÎҼǵÃÓÐÈËÇ¡µ±µØ½«ÕâÖÖ²ßÂÔ³ÆΪÑó´ÐÁ´"·½·¨.

ÖÁÉÙÔÚ GCC µÄ C++ ±ê×¼¿âʵÏÖÖÐÊÇÕâÑùµÄ(ÀýÈ磬Çë²Î¼û ´Ë´¦).Õâ¾ÍÊÇ MSVC ±ê×¼¿â°æ±¾ÖÐ¾É Dimkumware µÄ STL ÒÔ¼° MSVC Ò»Ö±µ½ VS2013 µÄËùÓа汾ÖеÄÇé¿ö.

È»¶ø£¬VS2015 ÌṩµÄ±ê×¼¿âͻȻ²»ÔÙ×ñÑ­ÕâÖÖÅÅÐò²ßÂÔ.VS2015 ¸½´øµÄ¿âʹÓÃÁËÒ»ÖÖÏ൱¼òµ¥µÄ×Ô¶¥ÏòϹ鲢ÅÅÐòµÄµÝ¹éʵÏÖ.ÕâÈÃÎÒ¾õµÃºÜÆæ¹Ö£¬ÒòΪ×ÔÉ϶øϵķ½·¨ÐèÒª·ÃÎÊÁбíµÄÖеã²ÅÄܽ«Æä·Ö³ÉÁ½°ë.ÓÉÓÚ std::list<> ²»Ö§³ÖËæ»ú·ÃÎÊ£¬ÕÒµ½ÖеãµÄΨһ·½·¨ÊÇÖð×Öµü´úÁбíµÄÒ»°ë.´ËÍ⣬һ¿ªÊ¼¾ÍÐèÒªÖªµÀÁбíÖÐÔªËصÄ×ÜÊý(ÔÚ C++11 ֮ǰ²»Ò»¶¨ÊÇ O(1) ÔËËã).

¾¡¹ÜÈç´Ë£¬VS2015 ÖÐµÄ std::list<>::sort() ÕýÊÇÕâÑù×öµÄ.ÕâÊǸÃʵÏÖµÄժ¼£¬Ëü¶¨Î»Öе㲢ִÐеݹéµ÷ÓÃ

<´úÂë>...µü´úÆ÷ _Mid = _STD next(_First, _Size/2);_First = _Sort(_First, _Mid, _Pred, _Size/2);_Mid = _Sort(_Mid, _Last, _Pred, _Size - _Size/2);...

ÈçÄúËù¼û£¬ËûÃÇÖ»ÊÇÂþ²»¾­ÐĵØʹÓà std::next ±éÀúÁбíµÄÇ°°ë²¿·Ö²¢µ½´ï _Mid µü´úÆ÷.

ÎÒÏëÖªµÀÕâ¸öת»»±³ºóµÄÔ­ÒòÊÇʲô?ÎÒËù¿´µ½µÄÖ»ÊÇÔÚÿ¸öµÝ¹é¼¶±ðÖظ´µ÷Óà std::next µÄЧÂʵÍÏÂ.ÌìÕæµÄÂß¼­ËµÕâÊÇÂý.Èç¹ûËûÃÇÔ¸Ò⸶³öÕâÑùµÄ´ú¼Û£¬ËûÃǺܿÉÄÜÏ£ÍûµÃµ½Ò»Ð©»Ø±¨.ÄÇËûÃǵõ½Ê²Ã´?ÎÒ²¢Ã»ÓÐÁ¢¼´¿´µ½Õâ¸öËã·¨¾ßÓиüºÃµÄ»º´æÐÐΪ(ÓëԭʼµÄ×Ôµ×ÏòÉÏ·½·¨Ïà±È).ÎÒ²¢Ã»ÓÐÁ¢¼´ÈÏΪËüÔÚÔ¤ÏÈÅÅÐòµÄÐòÁÐÉϱíÏÖ¸üºÃ.

µ±È»£¬ÓÉÓÚC++11 std::list<> »ù±¾ÉÏÐèÒª´æ´¢ËüµÄÔªËؼÆÊý£¬ÕâʹµÃÉÏÃæµÄЧÂÊÉÔ΢¸ßһЩ£¬ÒòΪÎÒÃÇ×ÜÊÇÌáÇ°ÖªµÀÔªËؼÆÊý.µ«ÕâËƺõÈÔÈ»²»×ãÒÔÖ¤Ã÷ÔÚÿ¸öµÝ¹é¼¶±ðÉϽøÐÐ˳ÐòɨÃèÊǺÏÀíµÄ.

(³ÏÈ»£¬ÎÒûÓг¢ÊÔÔÚʵÏÖÖ®¼ä½øÐоºÕù.Ò²ÐíÄÇÀïÓÐһЩ¾ªÏ².)

½â¾ö·½°¸

Çë×¢Ò⣬´Ë´ð°¸ÒѸüУ¬ÒÔ½â¾öÒÔÏÂÆÀÂÛÖкÍÎÊÌâÖ®ºóÌáµ½µÄËùÓÐÎÊÌ⣬·½·¨ÊÇ´ÓÁбíÊý×éµ½Ò»¸öµü´úÆ÷Êý×飬ͬʱ±£ÁôÁ˸ü¿ìµÄ×Ôµ×ÏòÉϹ鲢ÅÅÐòËã·¨£¬²¢Ïû³ýÁË×Ô¶¥ÏòϹ鲢ÅÅÐòËã·¨µÝ¹éµ¼Ö¶ÑÕ»Òç³öµÄС¸ÅÂÊ.

ÎÒ×î³õûÓп¼Âǵü´úÆ÷µÄÔ­ÒòÊÇÓÉÓÚ VS2015 ¸ü¸ÄΪ×Ô¶¥ÏòÏ£¬ÈÃÎÒÏàÐų¢ÊÔ¸ü¸ÄÏÖÓÐ×Ôµ×ÏòÉÏËã·¨ÒÔʹÓõü´úÆ÷´æÔÚһЩÎÊÌ⣬ÐèÒªÇл»µ½½ÏÂýµÄ¶¥²¿ÏÂËã·¨.Ö»Óе±ÎÒ³¢ÊÔ×Ô¼º·ÖÎöÇл»µ½µü´úÆ÷ʱ£¬ÎÒ²ÅÒâʶµ½ÓÐÒ»¸ö×Ôµ×ÏòÉÏËã·¨µÄ½â¾ö·½°¸.

ÔÚ@sbi µÄÆÀÂÛÖУ¬ËûѯÎÊÁË×ÔÉ϶øÏ·½·¨µÄ×÷Õß Stephan T. Lavavej£¬ÎªÊ²Ã´Òª½øÐиü¸Ä.Stephan µÄ»ØÓ¦ÊDZÜÃâÄÚ´æ·ÖÅäºÍĬÈϹ¹Ôì·ÖÅäÆ÷".VS2015 ÒýÈëÁ˲»¿ÉĬÈϹ¹ÔìºÍÓÐ״̬µÄ·ÖÅäÆ÷£¬ÕâÔÚʹÓÃÏÈÇ°°æ±¾µÄÁбíÊý×éʱ»á³öÏÖÎÊÌ⣬ÒòΪÁбíµÄÿ¸öʵÀý·ÖÅäÒ»¸öÐéÄâ½Úµã£¬²¢ÇÒÐèÒª½øÐиü¸ÄÒÔ´¦ÀíÎÞĬÈÏ·ÖÅäÆ÷.

Lavavej µÄ½â¾ö·½°¸ÊǸÄÓõü´úÆ÷À´¸ú×ÙԭʼÁбíÖеÄÔËÐб߽磬¶ø²»ÊÇÄÚ²¿ÁбíÊý×é.ºÏ²¢Âß¼­¸ÄΪʹÓà 3 ¸öµü´úÆ÷²ÎÊý£¬µÚÒ»¸ö²ÎÊýÊÇ×óÔËÐпªÊ¼µÄµü´úÆ÷£¬µÚ¶þ¸ö²ÎÊýÊÇ×óÔËÐнáÊøµÄµü´úÆ÷ == ÓÒÔËÐпªÊ¼µÄµü´úÆ÷£¬µÚÈý¸ö²ÎÊýÊÇÓÒÔËÐнáÊøµÄµü´úÆ÷.ºÏ²¢¹ý³ÌʹÓà std::list::splice Ôںϲ¢²Ù×÷ÆÚ¼äÒƶ¯Ô­Ê¼ÁбíÖеĽڵã.Õâ¾ßÓÐÒì³£°²È«µÄ¶îÍâºÃ´¦.Èç¹ûµ÷ÓÃÕߵıȽϺ¯ÊýÅ׳öÒì³££¬ÁÐ±í½«±»ÖØÐÂÅÅÐò£¬µ«²»»á·¢ÉúÊý¾Ý¶ªÊ§(¼ÙÉèÆ´½Ó²»»áʧ°Ü).ʹÓÃ֮ǰµÄ·½°¸£¬Èç¹û·¢ÉúÒì³££¬²¿·Ö(»ò´ó²¿·Ö)Êý¾Ý½«ÔÚÁбíµÄÄÚ²¿Êý×éÖУ¬²¢ÇÒÊý¾Ý½«´ÓԭʼÁбíÖжªÊ§.

µ«ÊDz»ÐèÒªÇл»µ½×ÔÉ϶øϵĹ鲢ÅÅÐò.×î³õ£¬ÎÒÈÏΪ VS2015 Çл»µ½×ÔÉ϶øÏÂÓÐһЩδ֪µÄÔ­Òò£¬ÎÒרעÓÚÒÔÓë std::list::splice ÏàͬµÄ·½Ê½Ê¹ÓÃÄÚ²¿½Ó¿Ú.ºóÀ´ÎÒ¾ö¶¨Ñо¿×Ô϶øÉϵÄÇл»ÒÔʹÓõü´úÆ÷Êý×é.ÎÒÒâʶµ½´æ´¢ÔÚÄÚ²¿Êý×éÖеÄÔËÐÐ˳ÐòÊÇ×îеÄ(Êý×é [0] = ×îÓÒ±ß)µ½×î¾ÉµÄ(Êý×é [×îºó] = ×î×ó±ß)£¬²¢ÇÒËü¿ÉÒÔʹÓÃÓë VS2015 ×ÔÉ϶øϵķ½·¨ÏàͬµÄ»ùÓÚµü´úÆ÷µÄºÏ²¢Âß¼­.

¶ÔÓÚ×Ô϶øÉϵĹ鲢ÅÅÐò£¬array[i] ÊÇÒ»¸öµü´úÆ÷£¬Ö¸Ïò¾ßÓÐ 2^i ¸ö½ÚµãµÄÒÑÅÅÐò×ÓÁбíµÄ¿ªÍ·£¬»òÕßËüΪ¿Õ(ʹÓà std::list::end ±íʾΪ¿Õ).ÿ¸öÅÅÐò×ÓÁбíµÄ½á⽫ÊÇÊý×éÖÐÏÂÒ»¸öÏÈÇ°·Ç¿ÕÌõÄ¿ÖÐÅÅÐò×ÓÁбíµÄ¿ªÍ·£¬»òÕßÈç¹ûÔÚÊý×éµÄ¿ªÍ·£¬ÔòÔÚ±¾µØµü´úÆ÷ÖÐ(ËüÖ¸Ïò×îеĽáβ)ÅÜ).Óë×Ô¶¥ÏòÏ·½·¨ÀàËÆ£¬µü´úÆ÷Êý×é½öÓÃÓÚ¸ú×ÙԭʼÁ´±íÄÚÒÑÅÅÐòµÄÔËÐб߽磬¶øºÏ²¢¹ý³ÌʹÓà std::list::splice Òƶ¯Ô­Ê¼Á´±íÄڵĽڵã.

Èç¹ûÒ»¸öÁ´±íºÜ´ó£¬½Úµã·ÖÉ¢£¬¾Í»áÓкܶ໺´æδÃüÖÐ.×Ô϶øÉϽ«±È×ÔÉ϶øÏ¿ìÔ¼ 30%(Ï൱ÓÚ×ÔÉ϶øϱÈ×Ô϶øÉÏÂýÔ¼ 42%).ÔÙ˵һ´Î£¬Èç¹ûÓÐ×ã¹»µÄÄڴ棬ͨ³£½«ÁбíÒƶ¯µ½Êý×é»òÏòÁ¿£¬¶ÔÊý×é»òÏòÁ¿½øÐÐÅÅÐò£¬È»ºó´ÓÅÅÐòºóµÄÊý×é»òÏòÁ¿´´½¨Ò»¸öÐÂÁбíͨ³£»á¸ü¿ì.

ʾÀý C++ ´úÂë:

#define ASZ 32Ä£°å void SortList(std::list<T> &ll){if (ll.size() < 2)//Èç¹ûÎÞÊ¿É×öÔò·µ»Ø·µ»Ø;std::list::iterator ai[ASZ];//µü´úÆ÷Êý×éstd::list::iterator mi;//Öмäµü´úÆ÷ (end lft, bgn rgt)std::list::iterator ei;//½áÊøµü´úÆ÷size_t i;for (i = 0; i typename std::list<T>::iterator Merge(std::list<T> &ll,ÀàÐÍÃû³Æ std::list<T>::iterator li,typename std::list<T>::iterator mi,ÀàÐÍÃû³Æ std::list::iterator ei){std::list::iterator ni;(*mi <*li) ?ni = mi : ni = li;¶ø(1){if(*mi <*li){ll.splice(li, ll, mi++);Èç¹û(mi == ei)·µ»Ø ni;} ±ðµÄ {if(++li == mi)·µ»Ø ni;}}}


VS2019 µÄ std::list::sort() Ìæ»»´úÂëʾÀý(ºÏ²¢Âß¼­±»ÖÆ×÷³ÉÒ»¸öµ¥¶ÀµÄÄÚ²¿º¯Êý£¬ÒòΪËüÏÖÔÚÔÚÁ½¸öµØ·½Ê¹ÓÃ).

˽ÓÐ:Ä£°å<class_Pr2>µü´úÆ÷_Merge(_Pr2 _Pred, µü´úÆ÷_First, µü´úÆ÷_Mid, µü´úÆ÷_Last){µü´úÆ÷_Newfirst = _First;for (bool _Initial_loop = true;;_Initial_loop = false) {//[_First, _Mid) ºÍ [_Mid, _Last) ÒÑÅÅÐòÇÒ·Ç¿Õif (_DEBUG_LT_PRED(_Pred, *_Mid, *_First)) {//ÏûºÄ_MidÈç¹û(_Initial_loop){_Newfirst = _Mid;//¸üзµ»ØÖµ}splice(_First, *this, _Mid++);Èç¹û(_Mid == _Last){·µ»Ø_Newfirst;//ºÄ¾¡ [_Mid, _Last);Íê±Ï}}else {//ÏûºÄ _First++_µÚÒ»£»Èç¹û(_First == _Mid){·µ»Ø_Newfirst;//ºÄ¾¡ [_First, _Mid);Íê±Ï}}}}Ä£°å<class_Pr2>void _Sort(µü´úÆ÷_First£¬µü´úÆ÷_Last£¬_Pr2 _Pred£¬size_type _Size) {//ÅÅÐò[_First, _Last)£¬Ê¹ÓÃ_Pred£¬ÏÈ·µ»Ønew//_Size ±ØÐëÊÇ´Ó _First µ½ _Last µÄ¾àÀëÈç¹û (_Size <2) {·µ»Ø;//ûÊÂ×ö}const size_t _ASZ = 32;//Êý×é´óСµü´úÆ÷_Ai[_ASZ];//ÒªÔËÐеĵü´úÆ÷Êý×éµü´úÆ÷_Mi;//Öмäµü´úÆ÷µü´úÆ÷_Li;//×îºó(½áÊø)µü´úÆ÷³ß´ç_t_I;//Ë÷Òýµ½_Aifor (_I = 0; _I <_ASZ; _I++)//¿Õ"´óÅú_Ai[_I] = _Last;//_Ai[] == _Last =>¿ÕÌõÄ¿//½«½ÚµãºÏ²¢µ½Êý×éÖÐfor (_Li = _First; _Li != _Last;) {_Mi = _Li++;¶ÔÓÚ (_I = 0; (_I <_ASZ) && _Ai[_I] != _Last; _I++) {_Mi = _Merge(_Pass_fn(_Pred), _Ai[_I], _Mi, _Li);_Ai[_I] = _Last;}Èç¹û(_I == _ASZ)_Ò»ÊÀ - ;_Ai[_I] = _Mi;}//ºÏ²¢Êý×éÔËÐÐΪµ¥´ÎÔËÐжÔÓÚ (_I = 0; _I <_ASZ && _Ai[_I] == _Last; _I++);_Mi = _Ai[_I++];¶ø (1) {¶ÔÓÚ (; _I < _ASZ && _Ai[_I] == _Last; _I++);Èç¹û(_I == _ASZ)ÐÝÏ¢;_Mi = _Merge(_Pass_fn(_Pred), _Ai[_I++], _Mi, _Last);}}


Õâ¸ö´ð°¸µÄÆäÓಿ·ÖÊÇÀúÊ·ÐÔµÄ.


ÎÒÄܹ»¸ù¾Ý@IgorTandetnik µÄÑÝʾÖØÏÖ¸ÃÎÊÌâ(¾ÉÀàÐÍÎÞ·¨±àÒ룬ÐÂÀàÐÍÓÐЧ):

#include #include <Áбí>#include <ÄÚ´æ>Ä£°å Àà MyAlloc : public std::allocator{ÉÏÊÐ:MyAlloc(T) {}//È¡ÏûĬÈϹ¹Ô캯ÊýÄ£°åMyAlloc(const MyAlloc<U>& other) : std::allocator<T>(other) {}Ä£°åstruct rebind { typedef MyAlloc;ÆäËû;};};int main(){std::list>l(MyAlloc(0))£»l.push_back(3);l.push_back(0);l.push_back(2);l.push_back(1);l.sort();·µ»Ø0£»}


ÎÒÔçÔÚ 2016 Äê 7 Ô¾Í×¢Òâµ½ÁËÕâÒ»±ä»¯£¬²¢ÓÚ 2016 Äê 8 Ô 1 ÈÕͨ¹ýµç×ÓÓʼþÏò P.J. Plauger ·¢ËÍÁËÓйØÕâÒ»±ä»¯µÄµç×ÓÓʼþ.ËûµÄ»Ø¸´ÕªÒª:

<¿éÒýÓÃ>

ÓÐȤµÄÊÇ£¬ÎÒÃǵĸü¸ÄÈÕÖ¾²¢Î´·´Ó³´Ë¸ü¸Ä.ÄÇ¿ÉÄÜÒâζ×ÅËüÊǽ¨ÒéµÄ"ÓÉÎÒÃǵÄһλ´ó¿Í»§ºÍÎÒÔÚ´úÂëÉó²éÖеõ½ÁË.ÎÒÏÖÔÚÖ»ÖªµÀ¸Ä±äÒѾ­µ½À´´óÔ¼ÔÚ 2015 ÄêÇïÌì.µ±ÎҲ鿴´úÂëʱ£¬µÚÒ»¸öÁîÎÒÓ¡ÏóÉî¿ÌµÄÊÇÕâÌõÏß:

 µü´úÆ÷ _Mid = _STD next(_First, _Size/2);

µ±È»£¬¶ÔÓÚÒ»¸ö´óÁÐ±í£¬Õâ¿ÉÄÜÐèÒªºÜ³¤Ê±¼ä.

´úÂë¿´ÆðÀ´±ÈÎÒÔÚ 1995 Äê³õдµÄ¸üÓÅÑÅ(£¡)£¬µ«¿Ï¶¨ÓиüÔã¸âµÄʱ¼ä¸´ÔÓ¶È.ÄǸö°æ±¾Êǽ¨Ä£µÄÔÚԭʼ STL ÖÐ Stepanov¡¢Lee ºÍ Musser µÄ·½·¨Ö®ºó.ËûÃÇÔÚË㷨ѡÔñÉϺÜÉÙ±»·¢ÏÖÊÇ´íÎóµÄ.

ÎÒÏÖÔÚÒª»Ö¸´µ½ÎÒÃÇ×îÐÂÒÑÖªµÄԭʼ´úÂëµÄÁ¼ºÃ°æ±¾.

ÎÒ²»ÖªµÀ P.J. Plauger »Ö¸´Ô­Ê¼´úÂëÊÇ·ñ½â¾öÁËеķÖÅäÆ÷ÎÊÌ⣬»òÕß Microsoft ÊÇ·ñ»òÈçºÎÓë Dinkumware ½»»¥.

ΪÁ˱ȽÏ×Ô¶¥ÏòϺÍ×Ôµ×ÏòÉÏ·½·¨£¬ÎÒ´´½¨ÁËÒ»¸ö°üº¬ 400 Íò¸öÔªËصÄÁ´±í£¬Ã¿¸öÔªËØÓÉÒ»¸ö 64 λÎÞ·ûºÅÕûÊý×é³É£¬¼ÙÉèÎÒ×îÖÕ»áµÃµ½Ò»¸ö¼¸ºõ°´Ë³ÐòÅÅÁеĽڵãµÄË«ÏòÁ´±í(¼´Ê¹ËüÃǻᱻ¶¯Ì¬·ÖÅä)£¬ÓÃËæ»úÊýÌî³äËüÃÇ£¬È»ºó¶ÔËüÃǽøÐÐÅÅÐò.½Úµã²»»áÒƶ¯£¬Ö»ÊÇÁ´½Ó·¢ÉúÁ˱仯£¬µ«ÏÖÔÚ±éÀúÁбíÒÔËæ»ú˳Ðò·ÃÎʽڵã.È»ºóÎÒÓÃÁíÒ»×éËæ»úÊýÌî³äÄÇЩËæ»úÅÅÐòµÄ½Úµã²¢ÔٴζÔËüÃǽøÐÐÅÅÐò.ÎÒ½« 2015 Äê×ÔÉ϶øϵķ½·¨Óë֮ǰΪƥÅä 2015 ÄêËù×öµÄÆäËû¸ü¸Ä¶øÐ޸ĵÄ×Ô϶øÉϵķ½·¨½øÐÐÁ˱ȽÏ(sort() ÏÖÔÚʹÓÃν´Ê±È½Ïº¯Êýµ÷Óà sort()£¬¶ø²»ÊǾßÓÐÁ½¸öµ¥¶ÀµÄº¯Êý).ÕâЩÊǽá¹û.¸üР- ÎÒÌí¼ÓÁËÒ»¸ö»ùÓÚ½ÚµãÖ¸ÕëµÄ°æ±¾£¬²¢×¢Òâµ½ÁË´ÓÁбíÖмòµ¥µØ´´½¨Ò»¸öÏòÁ¿¡¢ÅÅÐòÏòÁ¿¡¢¸´ÖÆ»ØÀ´µÄʱ¼ä.

˳Ðò½Úµã:2015°æ±¾1.6Ã룬֮ǰ°æ±¾1.5ÃëËæ»ú½Úµã:2015 °æ±¾ 4.0 Ã룬ÏÈÇ°°æ±¾ 2.8 ÃëËæ»ú½Úµã:»ùÓÚ½ÚµãÖ¸ÕëµÄ°æ±¾ 2.6 ÃëËæ»ú½Úµã:´ÓÁÐ±í´´½¨ÏòÁ¿£¬ÅÅÐò£¬¸´ÖÆ»Ø 1.25 Ãë

¶ÔÓÚ˳Ðò½Úµã£¬ÏÈÇ°°æ±¾Ö»ÊÇ¿ìÒ»µã£¬µ«¶ÔÓÚËæ»ú½Úµã£¬ÏÈÇ°°æ±¾¿ì 30%£¬½ÚµãÖ¸Õë°æ±¾¿ì 35%£¬²¢´ÓÁбíÖд´½¨Ò»¸öÏòÁ¿£¬¶ÔÏòÁ¿½øÐÐÅÅÐò£¬È»ºó¸´ÖÆ»ØÀ´µÄËÙ¶ÈÌá¸ßÁË 69%.

ÏÂÃæÊÇ std::list::sort() µÄµÚÒ»¸öÌæ»»´úÂ룬ÎÒÓÃÀ´±È½Ï֮ǰµÄ×Ô϶øÉϵÄСÊý×é (_BinList[]) ·½·¨Óë VS2015 µÄ×ÔÉ϶øϵķ½·¨£¬ÎÒÏ£Íû±È½Ï¹«Æ½£¬ËùÒÔÎÒÐÞ¸ÄÁË < µÄ¸±±¾Áбí >.

 void sort(){//ÅÅÐòÐòÁУ¬Ê¹ÓòÙ×÷·û<ÅÅÐò(ÉÙ<>())£»}Ä£°åÎÞЧÅÅÐò(_Pr2 _Pred){//¶©µ¥ÐòÁУ¬Ê¹Óà _PredÈç¹û (2 > this->_Mysize())·µ»Ø;const size_t _MAXBINS = 25;_Myt _Templist, _Binlist[_MAXBINS];¶ø(£¡¿Õ()){//_Templist = ÏÂÒ»¸öÔªËØ_Templist._Splice_same(_Templist.begin(), *this, begin(),++¿ªÊ¼()£¬1)£»//Óë¸ü´óµÄ bin Êý×éºÏ²¢size_t _Bin;for (_Bin = 0; _Bin < _MAXBINS && !_Binlist[_Bin].empty();++_Bin)_Templist.merge(_Binlist[_Bin], _Pred);//²»ÒªÔ½¹ýÊý×éµÄĩβÈç¹û(_Bin == _MAXBINS)_±ó--;//ʹÓúϲ¢Áбí¸üРbin£¬¿Õ _Templist_Binlist[_Bin].swap(_Templist);}//½« bin ºÏ²¢»Øµ÷ÓÃÕßÁбí¶ÔÓÚ (size_t _Bin = 0; _Bin <_MAXBINS; _Bin++)if(!_Binlist[_Bin].empty())this->merge(_Binlist[_Bin], _Pred);}

ÎÒ×öÁËһЩС¸Ä¶¯.ԭʼ´úÂëÔÚÃûΪ _Maxbin µÄ±äÁ¿Öиú×Ùʵ¼Ê×î´ó bin£¬µ«×îÖպϲ¢µÄ¿ªÏú×㹻С£¬ÎÒɾ³ýÁËÓë _Maxbin ¹ØÁªµÄ´úÂë.ÔÚÊý×é¹¹½¨Æڼ䣬ԭʼ´úÂëµÄÄÚ²¿Ñ­»·ºÏ²¢µ½ _Binlist[] ÔªËØ£¬È»ºó½»»»µ½ _Templist£¬ÕâËƺõºÁÎÞÒâÒå.ÎÒ½«ÄÚ²¿Ñ­»·¸ü¸ÄΪ½öºÏ²¢µ½ _Templist£¬½öÔÚÕÒµ½¿ÕµÄ _Binlist[] ÔªËغó²Å½øÐн»»».

ÏÂÃæÊÇÎÒÓÃÓÚÁíÒ»¸ö±È½ÏµÄ std::list::sort() µÄ»ùÓÚ½ÚµãÖ¸ÕëµÄÌæ»».ÕâÏû³ýÁËÓë·ÖÅäÏà¹ØµÄÎÊÌâ.Èç¹û¿ÉÄÜ·¢Éú±È½ÏÒì³£²¢ÇÒ·¢ÉúÁ˱ȽÏÒì³££¬Ôò±ØÐ뽫Êý×éºÍÁÙʱÁбí (pNode) ÖеÄËùÓнڵã×·¼Ó»ØԭʼÁÐ±í£¬·ñÔò±È½ÏÒì³£¿ÉÄܻᱻÊÓΪСÓڱȽÏ.

 void sort(){//ÅÅÐòÐòÁУ¬Ê¹ÓòÙ×÷·û<ÅÅÐò(ÉÙ<>())£»}Ä£°åÎÞЧÅÅÐò(_Pr2 _Pred){//¶©µ¥ÐòÁУ¬Ê¹Óà _Predconst size_t _NUMBINS = 25;_Nodeptr aList[_NUMBINS];//ÁбíÊý×é_Nodeptr pNode;_Nodeptr pNext;_Nodeptr pPrev;if (this->size() <2)//Èç¹ûÎÞÊ¿É×öÔò·µ»Ø·µ»Ø;this->_Myhead()->_Prev->_Next = 0;//ÉèÖÃ×îºóÒ»¸ö½Úµã ->_Next = 0pNode = this->_Myhead()->_Next;//½« ptr ÉèÖÃΪÁбíµÄ¿ªÍ·size_t i;for (i = 0; i <_NUMBINS; i++)//ÁãÊý×éaList[i] = 0;while (pNode != 0)//½«½ÚµãºÏ²¢µ½Êý×éÖÐ{pNext = pNode->_Next;pNode->_Next = 0;for (i = 0; (i <_NUMBINS) && (aList[i] != 0); i++){pNode = _MergeN(_Pred, aList[i], pNode);aList[i] = 0;}Èç¹û(ÎÒ == _NUMBINS)Ò»ÊÀ - ;aList[i] = pNode;pNode = pNext;}pNode = 0;//½«Êý×éºÏ²¢ÎªÒ»¸öÁбífor (i = 0; i <_NUMBINS; i++)pNode = _MergeN(_Pred, aList[i], pNode);this->_Myhead()->_Next = pNode;//¸üÐÂÉÚ±ø½ÚµãÁ´½ÓpPrev = this->_Myhead();//ºÍ _Prev Ö¸Õë¶ø (pNode){pNode->_Prev = pPrev;pPrev = pNode;pNode = pNode->_Next;}pPrev->_Next = this->_Myhead();this->_Myhead()->_Prev = pPrev;}Ä£°å_Nodeptr _MergeN(_Pr2 &_Pred, _Nodeptr pSrc1, _Nodeptr pSrc2){_Nodeptr pDst = 0;//Ä¿±êÍ·Ö¸Õë_Nodeptr *ppDst = &pDst;//Ö¸ÏòÍ·²¿»òÉÏÒ»¸öµÄÖ¸Õë->_ÏÂÒ»¸öÈç¹û(pSrc1 == 0)·µ»Ø pSrc2£»Èç¹û(pSrc2 == 0)·µ»Ø pSrc1;¶ø (1){if (_DEBUG_LT_PRED(_Pred, pSrc2->_Myval, pSrc1->_Myval)){*ppDst = pSrc2;pSrc2 = *(ppDst = &pSrc2->_Next);Èç¹û(pSrc2 == 0){*ppDst = pSrc1;ÐÝÏ¢;}}±ðµÄ{*ppDst = pSrc1;pSrc1 = *(ppDst = &pSrc1->_Next);Èç¹û(pSrc1 == 0){*ppDst = pSrc2;ÐÝÏ¢;}}}·µ»Ø pDst;}

I remember that since the beginning of times the most popular approach to implementing std::list<>::sort() was the classic Merge Sort algorithm implemented in bottom-up fashion (see also What makes the gcc std::list sort implementation so fast?).

I remember seeing someone aptly refer to this strategy as "onion chaining" approach.

At least that's the way it is in GCC's implementation of C++ standard library (see, for example, here). And this is how it was in old Dimkumware's STL in MSVC version of standard library, as well as in all versions of MSVC all the way to VS2013.

However, the standard library supplied with VS2015 suddenly no longer follows this sorting strategy. The library shipped with VS2015 uses a rather straightforward recursive implementation of top-down Merge Sort. This strikes me as strange, since top-down approach requires access to the mid-point of the list in order to split it in half. Since std::list<> does not support random access, the only way to find that mid-point is to literally iterate through half of the list. Also, at the very beginning it is necessary to know the total number of elements in the list (which was not necessarily an O(1) operation before C++11).

Nevertheless, std::list<>::sort() in VS2015 does exactly that. Here's an excerpt from that implementation that locates the mid-point and performs recursive calls

...
iterator _Mid = _STD next(_First, _Size / 2);
_First = _Sort(_First, _Mid, _Pred, _Size / 2);
_Mid = _Sort(_Mid, _Last, _Pred, _Size - _Size / 2);
...

As you can see, they just nonchalantly use std::next to walk through the first half of the list and arrive at _Mid iterator.

What could be the reason behind this switch, I wonder? All I see is a seemingly obvious inefficiency of repetitive calls to std::next at each level of recursion. Naive logic says that this is slower. If they are willing to pay this kind of price, they probably expect to get something in return. What are they getting then? I don't immediately see this algorithm as having better cache behavior (compared to the original bottom-up approach). I don't immediately see it as behaving better on pre-sorted sequences.

Granted, since C++11 std::list<> is basically required to store its element count, which makes the above slightly more efficient, since we always know the element count in advance. But that still does not seem to be enough to justify the sequential scan on each level of recursion.

(Admittedly, I haven't tried to race the implementations against each other. Maybe there are some surprises there.)

½â¾ö·½°¸

Note this answer has been updated to address all of the issues mentioned in the comments below and after the question, by making the same change from an array of lists to an array of iterators, while retaining the faster bottom up merge sort algorithm, and eliminating the small chance of stack overflow due to recursion with the top down merge sort algorithm.

The reason I didn't originally consider iterators was due to the VS2015 change to top down, leading me to believe there was some issue with trying to change the existing bottom up algorithm to use iterators, requiring a switch to the slower top down algorithm. It was only when I tried to analyze the switch to iterators myself that I realized there was a solution for bottom up algorithm.

In @sbi's comment, he asked the author of the top down approach, Stephan T. Lavavej, why the change was made. Stephan's response was "to avoid memory allocation and default constructing allocators". VS2015 introduced non-default-constructible and stateful allocators, which presents an issue when using the prior version's array of lists, as each instance of a list allocates a dummy node, and a change would be needed to handle no default allocator.

Lavavej's solution was to switch to using iterators to keep track of run boundaries within the original list instead of an internal array of lists. The merge logic was changed to use 3 iterator parameters, 1st parameter is iterator to start of left run, 2nd parameter is iterator to end of left run == iterator to start of right run, 3rd parameter is iterator to end of right run. The merge process uses std::list::splice to move nodes within the original list during merge operations. This has the added benefit of being exception safe. If a caller's compare function throws an exception, the list will be re-ordered, but no loss of data will occur (assuming splice can't fail). With the prior scheme, some (or most) of the data would be in the internal array of lists if an exception occurred, and data would be lost from the original list.

However the switch to top down merge sort was not needed. Initially, thinking there was some unknown to me reason for VS2015 switch to top down, I focused on using the internal interfaces in the same manner as std::list::splice. I later decided to investigate switching bottom up to use an array of iterators. I realized the order of runs stored in the internal array was newest (array[0] = rightmost) to oldest (array[last] = leftmost), and that it could use the same iterator based merge logic as VS2015's top down approach.

For bottom up merge sort, array[i] is an iterator to the start of a sorted sub-list with 2^i nodes, or it is empty (using std::list::end to indicate empty). The end of each sorted sub-list will be the start of a sorted sub-list in the next prior non-empty entry in the array, or if at the start of the array, in a local iterator (it points to end of newest run). Similar to the top down approach, the array of iterators is only used to keep track of sorted run boundaries within the original linked list, while the merge process uses std::list::splice to move nodes within the original linked list.

If a linked list is large and the nodes scattered, there will be a lot of cache misses. Bottom up will be about 30% faster than top down (equivalent to stating top down is about 42% slower than bottom up ). Then again, if there's enough memory, it would usually be faster to move the list to an array or vector, sort the array or vector, then create a new list from the sorted array or vector.

Example C++ code:

#define ASZ 32

template <typename T>
void SortList(std::list<T> &ll)
{
    if (ll.size() < 2)                  // return if nothing to do
        return;
    std::list<T>::iterator ai[ASZ];     // array of iterators
    std::list<T>::iterator mi;          // middle iterator (end lft, bgn rgt)
    std::list<T>::iterator ei;          // end    iterator
    size_t i;
    for (i = 0; i < ASZ; i++)           // "clear" array
        ai[i] = ll.end();
    // merge nodes into array
    for (ei = ll.begin(); ei != ll.end();) {
        mi = ei++;
        for (i = 0; (i < ASZ) && ai[i] != ll.end(); i++) {
            mi = Merge(ll, ai[i], mi, ei);
            ai[i] = ll.end();
        }
        if(i == ASZ)
            i--;
        ai[i] = mi;
    }
    // merge array into single list
    ei = ll.end();                              
    for(i = 0; (i < ASZ) && ai[i] == ei; i++);
    mi = ai[i++];
    while(1){
        for( ; (i < ASZ) && ai[i] == ei; i++);
        if (i == ASZ)
            break;
        mi = Merge(ll, ai[i++], mi, ei);
    }
}

template <typename T>
typename std::list<T>::iterator Merge(std::list<T> &ll,
                             typename std::list<T>::iterator li,
                             typename std::list<T>::iterator mi,
                             typename std::list<T>::iterator ei)
{
    std::list<T>::iterator ni;
    (*mi < *li) ? ni = mi : ni = li;
    while(1){
        if(*mi < *li){
            ll.splice(li, ll, mi++);
            if(mi == ei)
                return ni;
        } else {
            if(++li == mi)
                return ni;
        }
    }
}


Example replacement code for VS2019's std::list::sort() (the merge logic was made into a separate internal function, since it's now used in two places).

private:
    template <class _Pr2>
    iterator _Merge(_Pr2 _Pred, iterator _First, iterator _Mid, iterator _Last){
        iterator _Newfirst = _First;
        for (bool _Initial_loop = true;;
            _Initial_loop       = false) { // [_First, _Mid) and [_Mid, _Last) are sorted and non-empty
            if (_DEBUG_LT_PRED(_Pred, *_Mid, *_First)) { // consume _Mid
                if (_Initial_loop) {
                    _Newfirst = _Mid; // update return value
                }
                splice(_First, *this, _Mid++);
                if (_Mid == _Last) {
                    return _Newfirst; // exhausted [_Mid, _Last); done
                }
            }
            else { // consume _First
                ++_First;
                if (_First == _Mid) {
                    return _Newfirst; // exhausted [_First, _Mid); done
                }
            }
        }
    }

    template <class _Pr2>
    void _Sort(iterator _First, iterator _Last, _Pr2 _Pred,
        size_type _Size) { // order [_First, _Last), using _Pred, return new first
                           // _Size must be distance from _First to _Last
        if (_Size < 2) {
            return;        // nothing to do
        }
        const size_t _ASZ = 32;         // array size
        iterator _Ai[_ASZ];             // array of   iterators to runs
        iterator _Mi;                   // middle     iterator
        iterator _Li;                   // last (end) iterator
        size_t _I;                      // index to _Ai
        for (_I = 0; _I < _ASZ; _I++)   // "empty" array
            _Ai[_I] = _Last;            //   _Ai[] == _Last => empty entry
        // merge nodes into array
        for (_Li = _First; _Li != _Last;) {
            _Mi = _Li++;
            for (_I = 0; (_I < _ASZ) && _Ai[_I] != _Last; _I++) {
                _Mi = _Merge(_Pass_fn(_Pred), _Ai[_I], _Mi, _Li);
                _Ai[_I] = _Last;
            }
            if (_I == _ASZ)
                _I--;
            _Ai[_I] = _Mi;
        }
        // merge array runs into single run
        for (_I = 0; _I < _ASZ && _Ai[_I] == _Last; _I++);
        _Mi = _Ai[_I++];
        while (1) {
            for (; _I < _ASZ && _Ai[_I] == _Last; _I++);
            if (_I == _ASZ)
                break;
            _Mi = _Merge(_Pass_fn(_Pred), _Ai[_I++], _Mi, _Last);
        }
    }


The remainder of this answer is historical.


I was able to reproduce the issue (old sort fails to compile, new one works) based on a demo from @IgorTandetnik:

#include <iostream>
#include <list>
#include <memory>

template <typename T>
class MyAlloc : public std::allocator<T> {
public:
    MyAlloc(T) {}  // suppress default constructor
    
    template <typename U>
    MyAlloc(const MyAlloc<U>& other) : std::allocator<T>(other) {}
    
    template< class U > struct rebind { typedef MyAlloc<U> other; };
};

int main()
{
    std::list<int, MyAlloc<int>> l(MyAlloc<int>(0));
    l.push_back(3);
    l.push_back(0);
    l.push_back(2);
    l.push_back(1);
    l.sort();
    return 0;
}


I noticed this change back in July, 2016 and emailed P.J. Plauger about this change on August 1, 2016. A snippet of his reply:

Interestingly enough, our change log doesn't reflect this change. That probably means it was "suggested" by one of our larger customers and got by me on the code review. All I know now is that the change came in around the autumn of 2015. When I reviewed the code, the first thing that struck me was the line:

    iterator _Mid = _STD next(_First, _Size / 2);

which, of course, can take a very long time for a large list.

The code looks a bit more elegant than what I wrote in early 1995(!), but definitely has worse time complexity. That version was modeled after the approach by Stepanov, Lee, and Musser in the original STL. They are seldom found to be wrong in their choice of algorithms.

I'm now reverting to our latest known good version of the original code.

I don't know if P.J. Plauger's reversion to the original code dealt with the new allocator issue, or if or how Microsoft interacts with Dinkumware.

For a comparison of the top down versus bottom up methods, I created a linked list with 4 million elements, each consisting of one 64 bit unsigned integer, assuming I would end up with a doubly linked list of nearly sequentially ordered nodes (even though they would be dynamically allocated), filled them with random numbers, then sorted them. The nodes don't move, only the linkage is changed, but now traversing the list accesses the nodes in random order. I then filled those randomly ordered nodes with another set of random numbers and sorted them again. I compared the 2015 top down approach with the prior bottom up approach modified to match the other changes made for 2015 (sort() now calls sort() with a predicate compare function, rather than having two separate functions). These are the results. update - I added a node pointer based version and also noted the time for simply creating a vector from list, sorting vector, copy back.

sequential nodes: 2015 version 1.6 seconds, prior version 1.5  seconds
random nodes:     2015 version 4.0 seconds, prior version 2.8  seconds
random nodes:                  node pointer based version 2.6  seconds
random nodes:    create vector from list, sort, copy back 1.25 seconds

For sequential nodes, the prior version is only a bit faster, but for random nodes, the prior version is 30% faster, and the node pointer version 35% faster, and creating a vector from the list, sorting the vector, then copying back is 69% faster.

Below is the first replacement code for std::list::sort() I used to compare the prior bottom up with small array (_BinList[]) method versus VS2015's top down approach I wanted the comparison to be fair, so I modified a copy of < list >.

    void sort()
        {   // order sequence, using operator<
        sort(less<>());
        }

    template<class _Pr2>
        void sort(_Pr2 _Pred)
        {   // order sequence, using _Pred
        if (2 > this->_Mysize())
            return;
        const size_t _MAXBINS = 25;
        _Myt _Templist, _Binlist[_MAXBINS];
        while (!empty())
            {
            // _Templist = next element
            _Templist._Splice_same(_Templist.begin(), *this, begin(),
                ++begin(), 1);
            // merge with array of ever larger bins
            size_t _Bin;
            for (_Bin = 0; _Bin < _MAXBINS && !_Binlist[_Bin].empty();
                ++_Bin)
                _Templist.merge(_Binlist[_Bin], _Pred);
            // don't go past end of array
            if (_Bin == _MAXBINS)
                _Bin--;
            // update bin with merged list, empty _Templist
            _Binlist[_Bin].swap(_Templist);
            }
            // merge bins back into caller's list
            for (size_t _Bin = 0; _Bin < _MAXBINS; _Bin++)
                if(!_Binlist[_Bin].empty())
                    this->merge(_Binlist[_Bin], _Pred);
        }

I made some minor changes. The original code kept track of the actual maximum bin in a variable named _Maxbin, but the overhead in the final merge is small enough that I removed the code associated with _Maxbin. During the array build, the original code's inner loop merged into a _Binlist[] element, followed by a swap into _Templist, which seemed pointless. I changed the inner loop to just merge into _Templist, only swapping once an empty _Binlist[] element is found.

Below is a node pointer based replacement for std::list::sort() I used for yet another comparison. This eliminates allocation related issues. If a compare exception is possible and occurred, all the nodes in the array and temp list (pNode) would have to be appended back to the original list, or possibly a compare exception could be treated as a less than compare.

    void sort()
        {   // order sequence, using operator<
        sort(less<>());
        }

    template<class _Pr2>
        void sort(_Pr2 _Pred)
        {   // order sequence, using _Pred
        const size_t _NUMBINS = 25;
        _Nodeptr aList[_NUMBINS];           // array of lists
        _Nodeptr pNode;
        _Nodeptr pNext;
        _Nodeptr pPrev;
        if (this->size() < 2)               // return if nothing to do
            return;
        this->_Myhead()->_Prev->_Next = 0;  // set last node ->_Next = 0
        pNode = this->_Myhead()->_Next;     // set ptr to start of list
        size_t i;
        for (i = 0; i < _NUMBINS; i++)      // zero array
            aList[i] = 0;
        while (pNode != 0)                  // merge nodes into array
            {
            pNext = pNode->_Next;
            pNode->_Next = 0;
            for (i = 0; (i < _NUMBINS) && (aList[i] != 0); i++)
                {
                pNode = _MergeN(_Pred, aList[i], pNode);
                aList[i] = 0;
                }
            if (i == _NUMBINS)
                i--;
            aList[i] = pNode;
            pNode = pNext;
            }
        pNode = 0;                          // merge array into one list
        for (i = 0; i < _NUMBINS; i++)
            pNode = _MergeN(_Pred, aList[i], pNode);
        this->_Myhead()->_Next = pNode;     // update sentinel node links
        pPrev = this->_Myhead();            //  and _Prev pointers
        while (pNode)
            {
            pNode->_Prev = pPrev;
            pPrev = pNode;
            pNode = pNode->_Next;
            }
        pPrev->_Next = this->_Myhead();
        this->_Myhead()->_Prev = pPrev;
        }

    template<class _Pr2>
        _Nodeptr _MergeN(_Pr2 &_Pred, _Nodeptr pSrc1, _Nodeptr pSrc2)
        {
        _Nodeptr pDst = 0;          // destination head ptr
        _Nodeptr *ppDst = &pDst;    // ptr to head or prev->_Next
        if (pSrc1 == 0)
            return pSrc2;
        if (pSrc2 == 0)
            return pSrc1;
        while (1)
            {
            if (_DEBUG_LT_PRED(_Pred, pSrc2->_Myval, pSrc1->_Myval))
                {
                *ppDst = pSrc2;
                pSrc2 = *(ppDst = &pSrc2->_Next);
                if (pSrc2 == 0)
                    {
                    *ppDst = pSrc1;
                    break;
                    }
                }
            else
                {
                *ppDst = pSrc1;
                pSrc1 = *(ppDst = &pSrc1->_Next);
                if (pSrc1 == 0)
                    {
                    *ppDst = pSrc2;
                    break;
                    }
                }
            }
        return pDst;
        }

Õâƪ¹ØÓÚ`std::list&lt;&gt;::sort()` - ΪʲôͻȻÇл»µ½×ÔÉ϶øϵIJßÂÔ?µÄÎÄÕ¾ͽéÉܵ½ÕâÁË£¬Ï£ÍûÎÒÃÇÍƼöµÄ´ð°¸¶Ô´ó¼ÒÓÐËù°ïÖú£¬Ò²Ï£Íû´ó¼Ò¶à¶àÖ§³Ö¸ú°æÍø£¡