std::lexicographical_compare

函數原型:ios

default (1)
template <class InputIterator1, class InputIterator2>
  bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1,
                                InputIterator2 first2, InputIterator2 last2);
custom (2)
template <class InputIterator1, class InputIterator2, class Compare>
  bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1,
                                InputIterator2 first2, InputIterator2 last2,
                                Compare comp);
函數用途:

按照詞典序比較前者是否小於後者。函數

當序列<first1, last1>按照字典序比較小於後者序列<first2, last2>,則返回true。不然,返回false。性能

所謂字典序比較,指的是兩個序列分別從第一個開始一一按照字典序進行比較,若是相同位置的元素相同,則繼續向後比較,直到相同位置出現不一樣的元素爲止。spa

示例:code

// lexicographical_compare example
#include <iostream> // std::cout, std::boolalpha
#include <algorithm> // std::lexicographical_compare
#include <cctype> // std::tolower

// a case-insensitive comparison function:
bool mycomp (char c1, char c2)
{ return std::tolower(c1)<std::tolower(c2); }

int main () {
  char foo[]="Apple";
  char bar[]="apartment";

  std::cout << std::boolalpha;

  std::cout << "Comparing foo and bar lexicographically (foo<bar):\n";

  std::cout << "Using default comparison (operator<): ";
  std::cout << std::lexicographical_compare(foo,foo+5,bar,bar+9);
  std::cout << '\n';

  std::cout << "Using mycomp as comparison object: ";
  std::cout << std::lexicographical_compare(foo,foo+5,bar,bar+9,mycomp);
  std::cout << '\n';

  return 0;
}
默認比較函數,使用 ASCII 進行比較,例如本例中'A'爲65, 'a'爲97,所以'a'>'A'。

自定義的比較函數mycomp中,將全部的字符轉換成爲小寫,因此第一個未匹配的字符是第三個的'p'和'a'。orm

輸出:ci

Comparing foo and bar lexicographically (foo<bar):
Using default comparison (operator<): true
Using mycomp as comparison object: false

性能分析:原型

最多比較次數爲: 2*min(count1,count2)it


版權聲明:本文爲博主原創文章,未經博主容許不得轉載。io

本站公眾號
   歡迎關注本站公眾號,獲取更多信息