泛型算法系列36:lexicographical_compare()

#include <algorithm> #include <list> #include <string> #include <assert.h> #include <iostream> using namespace std; class size_compare { public: bool operator()( const string &a, const string &b ) { bool ret = (a.length() < b.length()); return ret; } }; /************************************************************************/ /* */ template<class _InIt1, class _InIt2> inline bool __CLRCALL_OR_CDECL my_Lexicographical_compare(_InIt1 _First1, _InIt1 _Last1, _InIt2 _First2, _InIt2 _Last2) { // order [_First1, _Last1) vs. [First2, Last2) _DEBUG_RANGE(_First1, _Last1); _DEBUG_RANGE(_First2, _Last2); for (; _First1 != _Last1 && _First2 != _Last2; ++_First1, ++_First2) { if (_DEBUG_LT(*_First1, *_First2)) return (true); else if (*_First2 < *_First1) return (false); } return (_First1 == _Last1 && _First2 != _Last2); } template<class _InIt1, class _InIt2, class _Pr> inline bool __CLRCALL_OR_CDECL my_Lexicographical_compare(_InIt1 _First1, _InIt1 _Last1, _InIt2 _First2, _InIt2 _Last2, _Pr _Pred) { // order [_First1, _Last1) vs. [First2, Last2) using _Pred _DEBUG_RANGE(_First1, _Last1); _DEBUG_RANGE(_First2, _Last2); _DEBUG_POINTER(_Pred); for (; _First1 != _Last1 && _First2 != _Last2; ++_First1, ++_First2) { if (_DEBUG_LT_PRED(_Pred, *_First1, *_First2)) return (true); else if (_Pred(*_First2, *_First1)) return (false); } return (_First1 == _Last1 && _First2 != _Last2); } /************************************************************************/ int main() { string arr1[] = { "Piglet", "Pooh", "Tigger" }; string arr2[] = { "Piglet", "Pooch", "Eeyore" }; bool res; // evaluates to false at second element // Pooch is less than Pooh // would also evaluate false at third element res = my_Lexicographical_compare( arr1, arr1 + 3, arr2, arr2 + 3 ); assert( res == false ); // evaluates to true: each element of ilist2 // has a length less than or equal to the // associated ilist1 element list< string > ilist1( arr1, arr1 + 3 ); list< string > ilist2( arr2, arr2 + 3 ); res = my_Lexicographical_compare( ilist1.begin(), ilist1.end(), ilist2.begin(), ilist2.end(), size_compare() ); assert( res == true ); cout << "ok: lexicographical_compare succeeded!/n"; return 0; }

 

//重载1,如果[first1, last1)按字典序列小于[first2, last2),返回true,否则返回false。

//重载2,功能同重载1,增加了比较函数comp,即大小关系由comp函数确定。

你可能感兴趣的:(Algorithm,算法,String,list,less,Class)