首页 > 代码库 > std::lexicographical_compare

std::lexicographical_compare

函数原型:

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。

所谓字典序比较,指的是两个序列分别从第一个开始一一按照字典序进行比较,如果相同位置的元素相同,则继续向后比较,直到相同位置出现不同的元素为止。

示例:

// 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‘。

输出:

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

性能分析:

最多比较次数为: 2*min(count1,count2)


std::lexicographical_compare