STL sort & virtual problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • izis777
    New Member
    • Oct 2008
    • 2

    STL sort & virtual problem

    I wanna sort the list with my class PrDerived. But, it doesn't occur. I think sort function creates a predicate copy and doesn't copies a virtual table. How to solve this problem ? See example:

    Code:
    	
    	list<int> List;
    	...
    	struct PrBase
    	{
    		virtual bool operator()(const int& a, const int& b) const
    		{
    			...
    		}
    	};
    
    	struct PrDerived : PrBase
    	{
    		virtual bool operator()(const int& a, const int& b) const
    		{
    			...
    		}
    	};
    
    	PrDerived MyDerived;
    	PrBase * p = &MyDerived;
    	List.sort( *p );
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    The function list::sort takes a function pointer to compare two of its elements. What you are giving it is a struct. I don't think this was what you were going for: perhaps you meant p->operator()? You example is confusing to me, but then I've never had much luck wrapping my head around function pointers.

    Comment

    • izis777
      New Member
      • Oct 2008
      • 2

      #3
      Originally posted by Ganon11
      The function list::sort takes a function pointer to compare two of its elements. What you are giving it is a struct. I don't think this was what you were going for: perhaps you meant p->operator()? You example is confusing to me, but then I've never had much luck wrapping my head around function pointers.
      sort() and stable_sort() sort all elements by using the binary predicate!
      Functional arguments for algorithms don't have to be functions. They can be objects that behave as functions. Such an object is called a function object, or functor.

      Comment

      Working...