Abhishek Gupta Abhishek Gupta - 1 month ago 7
C++ Question

C++ Template error

I trying to use sort algorithm for sorting the elements of a vector.
This is my code snippet.

Comparator

struct comparator
{
bool operator() ( OptVector<pair<int, pair<CgpPop*,CgpPop*> > >::iterator it1, OptVector<pair<int, pair<CgpPop*,CgpPop*> > >::iterator it2)
{
return ( ((*it1).first) < ((*it2).first));
}
} o_comparator;


My Vector - Here OptVector is a wrapper over vector which behaves in same manner as standard c++ vector.

OptVector< pair<int, pair<CgpPop*,CgpPop*> > > pll_units;


call to sort algo

sort<OptVector< pair<int, pair<CgpPop*,CgpPop*> > >::iterator > (pll_units.begin(), pll_units.end(), o_comparator);


But compiler throws following error

/calm/svr/sql/generic/stlinclude/stl/_algo.c: In function ‘const _Tp& _STL::__median(const _Tp&, const _Tp&, const _Tp&, _Compare) [with _Tp = _STL::pair<int, _STL::pair<CgpPop*, CgpPop*> >, _Compare = comparator]’:
/calm/svr/sql/generic/stlinclude/stl/_algo.c:820: instantiated from ‘void _STL::__introsort_loop(_RandomAccessIter, _RandomAccessIter, _Tp*, _Size, _Compare) [with _RandomAccessIter = _STL::pair<int, _STL::pair<CgpPop*, CgpPop*> >*, _Tp = _STL::pair<int, _STL::pair<CgpPop*, CgpPop*> >, _Size = long int, _Compare = comparator]’
/calm/svr/sql/generic/stlinclude/stl/_algo.c:841: instantiated from ‘void _STL::sort(_RandomAccessIter, _RandomAccessIter, _Compare) [with _RandomAccessIter = _STL::pair<int, _STL::pair<CgpPop*, CgpPop*> >*, _Compare = comparator]’
/calm/svr/sql/generic/source/codegen/cgpop.cpp:1249: instantiated from here
/calm/svr/sql/generic/stlinclude/stl/_algo.c:78: error: no match for call to ‘(comparator) (const _STL::pair<int, _STL::pair<CgpPop*, CgpPop*> >&, const _STL::pair<int, _STL::pair<CgpPop*, CgpPop*> >&)’
/calm/svr/sql/generic/source/codegen/cgpop.cpp:1192: note: candidates are: bool comparator::operator()(_STL::pair<int, _STL::pair<CgpPop*, CgpPop*> >*, _STL::pair<int, _STL::pair<CgpPop*, CgpPop*> >*)
/calm/svr/sql/generic/stlinclude/stl/_algo.c:79: error: no match for call to ‘(comparator) (const _STL::pair<int, _STL::pair<CgpPop*, CgpPop*> >&, const _STL::pair<int, _STL::pair<CgpPop*, CgpPop*> >&)’
/calm/svr/sql/generic/source/codegen/cgpop.cpp:1192: note: candidates are: bool comparator::operator()(_STL::pair<int, _STL::pair<CgpPop*, CgpPop*> >*, _STL::pair<int, _STL::pair<CgpPop*, CgpPop*> >*)


Could any one please suggest me what is my mistake ?

Answer

The comparator functor is supposed to take the elements but not the iterators as the parameter for comparing.

You should change the parameter type of comparator::operator() from iterator to value type:

struct comparator
{
    bool operator() ( const pair<int, pair<CgpPop*,CgpPop*> > & lhs, const pair<int, pair<CgpPop*,CgpPop*> > & rhs) const
    {
        return lhs.first < rhs.first;
    }
};

BTW: Making operator() const member function is a good habit.

Comments