For the comparison:
class pointer_less{public: template <typename T> bool operator()(const T* lhs, const T* rhs) const { return *lhs < *rhs; }};
Something like this for generic outputting:
template <typename CharT = char, typename Traits = std::char_traits<CharT> >class pointer_print{public: typedef std::basic_ostream<CharT, Traits> ostream_type; typedef std::basic_string<CharT, Traits> string_type; public: pointer_print(ostream_type& out) : os_(out) {} pointer_print(ostream_type& out, const string_type& separate) : os_(out), sep_(separate) {} pointer_print(const pointer_print& rhs) : os_(rhs.os_), sep_(rhs.sep_) {} template <typename T> void operator()(const T* obj) { os_ << *obj << sep_; } private: ostream_type& os_; string_type sep_;};
For deleting the objects from the list:
class single_delete{public: template <typename T> void operator()(T*& ptr) const { delete ptr; ptr = 0; }};
And a little example test program:
int main(){ std::list<int*> L; for (int i = 10; i > 0; --i) L.push_back( new int(i) ); std::cout << "Initial list:" << std::endl << std::endl; std::for_each( L.begin(), L.end(), pointer_print(std::cout, "\n") ); L.sort( pointer_less() ); std::cout << std::endl << "Sorted list: " << std::endl << std::endl; std::for_each( L.begin(), L.end(), pointer_print(std::cout, "\n") ); std::for_each( L.begin(), L.end(), single_delete() ); L.clear(); std::cout << "Press any key to continue..."; std::cin.get(); return 0;}
Edit: Something tells me the compiler wouldn't like "
templaete
". [ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || CUJ || MSVC++ Library Fixes || BarrysWorld || E-Mail Me ]
[edited by - Lektrix on October 12, 2003 4:29:27 AM]