Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <functional>
- #include <algorithm>
- #include <iostream>
- #include <cstdlib>
- #include <vector>
- //#define USE_BOOST
- #define STABLE
- #ifdef USE_BOOST
- #include <boost/shared_ptr.hpp>
- #else
- #include <memory>
- #endif
- class Object
- {
- public:
- Object( int theDepth )
- : depth( theDepth )
- {
- }
- int GetDepth() const
- {
- return depth;
- }
- private:
- int depth;
- };
- #ifdef DO_BOOST
- typedef boost::shared_ptr< Object > ObjectPtr;
- #else
- typedef std::shared_ptr< Object > ObjectPtr;
- #endif
- typedef std::vector< ObjectPtr > ObjectList;
- typedef std::function< bool( ObjectPtr, ObjectPtr ) > ObjectComparer;
- typedef std::function< void( ObjectList::iterator, ObjectList::iterator, ObjectComparer ) > ObjectSorter;
- void Sort( ObjectList& objects, ObjectSorter sortFunc )
- {
- auto sorterRaw = []( ObjectPtr ptr1, ObjectPtr ptr2 ) -> bool
- {
- auto obj1 = ptr1.get();
- auto obj2 = ptr2.get();
- if ( obj1->GetDepth() == obj2->GetDepth() )
- {
- return false;
- }
- return obj1->GetDepth() > obj2->GetDepth();
- };
- using namespace std::placeholders;
- ObjectComparer sorter = std::bind( sorterRaw, _1, _2 );
- sortFunc( objects.begin(), objects.end(), sorter );
- }
- int main()
- {
- ObjectList objects;
- for ( size_t i = 0; i < 100; ++i )
- {
- objects.push_back( ObjectPtr( new Object( rand() % 10 ) ) );
- }
- ObjectSorter sort( &std::sort< ObjectList::iterator, ObjectComparer > );
- ObjectSorter stableSort( &std::stable_sort< ObjectList::iterator, ObjectComparer > );
- #ifdef STABLE
- Sort( objects, stableSort );
- #else
- Sort( objects, sort );
- #endif
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement