Advertisement
spacechase0

std::stable_sort Fail

Oct 31st, 2011
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. #include <functional>
  2. #include <algorithm>
  3. #include <iostream>
  4. #include <cstdlib>
  5. #include <vector>
  6.  
  7. //#define USE_BOOST
  8. #define STABLE
  9.  
  10. #ifdef USE_BOOST
  11.     #include <boost/shared_ptr.hpp>
  12. #else
  13.     #include <memory>
  14. #endif
  15.  
  16. class Object
  17. {
  18.     public:
  19.         Object( int theDepth )
  20.            : depth( theDepth )
  21.         {
  22.         }
  23.        
  24.         int GetDepth() const
  25.         {
  26.             return depth;
  27.         }
  28.    
  29.     private:
  30.         int depth;
  31. };
  32. #ifdef DO_BOOST
  33.     typedef boost::shared_ptr< Object > ObjectPtr;
  34. #else
  35.     typedef std::shared_ptr< Object > ObjectPtr;
  36. #endif
  37. typedef std::vector< ObjectPtr > ObjectList;
  38. typedef std::function< bool( ObjectPtr, ObjectPtr ) > ObjectComparer;
  39. typedef std::function< void( ObjectList::iterator, ObjectList::iterator, ObjectComparer ) > ObjectSorter;
  40.  
  41. void Sort( ObjectList& objects, ObjectSorter sortFunc )
  42. {
  43.     auto sorterRaw = []( ObjectPtr ptr1, ObjectPtr ptr2 ) -> bool
  44.                      {
  45.                         auto obj1 = ptr1.get();
  46.                         auto obj2 = ptr2.get();
  47.                        
  48.                         if ( obj1->GetDepth() == obj2->GetDepth() )
  49.                         {
  50.                             return false;
  51.                         }
  52.                        
  53.                         return obj1->GetDepth() > obj2->GetDepth();
  54.                      };
  55.    
  56.     using namespace std::placeholders;
  57.     ObjectComparer sorter = std::bind( sorterRaw, _1, _2 );
  58.    
  59.     sortFunc( objects.begin(), objects.end(), sorter );
  60. }
  61.  
  62. int main()
  63. {
  64.     ObjectList objects;
  65.     for ( size_t i = 0; i < 100; ++i )
  66.     {
  67.         objects.push_back( ObjectPtr( new Object( rand() % 10 ) ) );
  68.     }
  69.    
  70.     ObjectSorter sort( &std::sort< ObjectList::iterator, ObjectComparer > );
  71.     ObjectSorter stableSort( &std::stable_sort< ObjectList::iterator, ObjectComparer > );
  72.    
  73.     #ifdef STABLE
  74.         Sort( objects, stableSort );
  75.     #else
  76.         Sort( objects, sort );
  77.     #endif
  78. }
  79.  
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement