天天看點

lexicographical_compare詳解

lexicographical_compare函數功能:按照字典順序比較前一區間是否小于後一區間.

template<class _InIt1,

         class _InTy,

         size_t _InSize,

         class _Pr> inline

         bool equal(_InIt1 _First1, _InIt1 _Last1,

                   _InTy (&_First2)[_InSize], _Pr _Pred)

         {       // compare [_First1, _Last1) to [First2, ...)

         return (_STD equal(_First1, _Last1,

                   _Array_iterator<_InTy, _InSize>(_First2), _Pred));

         }

 #endif

                   // TEMPLATE FUNCTION lexicographical_compare

template<class _InIt1,

         class _InIt2> inline

         bool _Lexicographical_compare(_InIt1 _First1, _InIt1 _Last1,

                   _InIt2 _First2, _InIt2 _Last2)

         {       // order [_First1, _Last1) vs. [First2, Last2)

         for (; _First1 != _Last1 && _First2 != _Last2; ++_First1, ++_First2)

                   if (_DEBUG_LT(*_First1, *_First2))//判斷是否*_First1<*_First2

                            return (true);

                   else if (*_First2 < *_First1)        //*_First1>*_First2

                            return (false);                               

                   //else  if *_First2 == *_First

         return (_First1 == _Last1 && _First2 != _Last2);

         }

另一重載函數不在贅述.

舉例:

int main()

{

         vector<int> vecInt;

         vecInt.push_back( 3 );

         vecInt.push_back( 6 );

         vecInt.push_back( 5 );

         list<int> lstInt;

         lstInt.push_back( 3 );

         lstInt.push_back( 12 );

         lstInt.push_back( 10 );

         lstInt.push_back( 6  );

         bool bLess = lexicographical_compare(vecInt.begin(),vecInt.end(),lstInt.begin(),lstInt.end() );

         system( "pause" );

         return 0;

}

需要注意的是,該算法的比較極易出現錯誤.例如:”111”,”12”.我們認為前者更大,但是實際上是後者更大,原因是長度在此根本不起作用.這類的有string

想要看string更詳細的易錯問題,請移步至: http://blog.csdn.net/yuanweihuayan/article/details/6641980

繼續閱讀