Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use std::multiset with multiple comparator function?

Good afternoon, I have a C++ class Range which implements a operator < for use by std::multiset<Range> ranges_type.

Since the multiset constructor don't specify a a custom comparator functor, it uses the std::less operator <.

However, I need to use a second comparator functor for std::multiset ranges_type. Specifically, I would specify a second comparator: std::multiset<Range, PointerCompare> where struct PointerCompare looks this :

struct PointerCompare{
   bool operator()(const Range& a, const Range& b) const {
         return (a.mPtr == b.mPtr)
   }

Is it possible to use std:multiset with multiple comparator functions or is there a workaround? Thank you

The class Range looks this:

class Range { 
     public:   
         explicit Range(int item){ 
            mLow = item;
            mHigh = item;
            mPtr  = 0;
         }
         Range(int low, int high, char* ptr = 0,char* mapptr = 0){ 
            mLow = low;
            mHigh = high;
            mPtr  = ptr;

         }
         Range(void){  
            mLow = 0;
            mHigh = 0;
            mPtr  = 0;

         }

         Range(const Range& r):
            mLow(r.mLow),
            mHigh(r.mHigh),
            mPtr(r.mPtr)
         {

         }


         bool operator==(const Range& rhs) const{
             return (mLow <= rhs.mLow && mHigh >= rhs.mHigh);
         }
         bool operator<(const Range& rhs) const{               
            return mHigh < rhs.mHigh;      
         } 
         int low() const { return mLow; }   
         int high() const { return mHigh; }
         char* getPtr() const { return mPtr; }
     private:   
         int mLow;   
         int mHigh; 
         char* mPtr;
}; // class Range 
like image 870
Frank Avatar asked Apr 29 '11 16:04

Frank


2 Answers

Sounds almost like you'd be better if you used something from Boost::MultiIndex rather than trying to force several different comparator functions onto a std::multiset. They have a bunch of different container types (see here.) In particular I'd look at the ordered_indices versions.

like image 164
wheaties Avatar answered Sep 29 '22 05:09

wheaties


I may have found a workaround for multiple comparator functions: Here it is:

Range targetRange = Range(PreviousNCopy,PreviousN, TmpPrevMapPtr);

bool Found = std::binary_search( ranges_type.begin(), ranges_type.end(), targetRange, MyComparator() );

where: MyComparator is a struct : struct MyComparator {
bool operator () ( const Range& d1, const Range& d2 ) const {
return d1.getPtr() < d2.getPtr();
} };

std::binary_search take o(log n) time but the std::multiset ranges_type must always remain sorted. Thank you.

like image 22
Frank Avatar answered Sep 29 '22 05:09

Frank