- template <class InputIterator1, class InputIterator2, class Compare>
- bool Lexicographical_compare(InputIterator1 first1, InputIterator1 last1,
- InputIterator2 first2, InputIterator2 last2,
- Compare comp) {
- for(; first1 != last1 && first2 != last2; ++first1, ++first2) {
- if(comp(*first1, *first2))
- return true;
- if(comp(*first2, *first1))
- return false;
- }
- return first1 == last1 && first2 != last2;
- }
效率至上的SGI还设计了一个特化版本,针对原生指针 const unsigned char*:
- inline bool lexicographical_compare(const unsigned char* first1,
- const unsigned char* last1,
- const unsigned char* first2,
- const unsigned char* last2) {
- const size_t len1 = last1 - first1;
- const size_t len2 = last2 - first2;
- const int result = memcmp(first1, first2, min(len1, len2));
- return result != 0 ? result < 0 : len1 < len2;
- }