我们这里只掌握lexicographical_compare的基本用法:
需要包含头文件 algorithm
(1)
template <class InputIterator1, class InputIterator2>
bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2);
(2)
template <class InputIterator1, class InputIterator2, class Compare>
bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
Compare comp);
lexicographical_compare全部用法的中文帮助文档:
https://www.apiref.com/cpp-zh/cpp/algorithm/lexicographical_compare.html
作用:
检查第一个范围 [first1, last1) 是否按字典序小于第二个范围 [first2, last2) 。
- 用 operator< 比较元素。
- 用给定的二元比较函数 comp 比较函数。
如果两个序列长度不同,并且短序列和长序列头部完全一样,例如example和examplee.那么,长度大的字典序比短序的大。
应用举例:
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(char c1, char c2)
{
return tolower(c1) < tolower(c2);
}
int main(void)
{
char first[] = "apple"; // 5 letters
char second[] = "Applement"; // 9 letters
if (lexicographical_compare(first, first + 5, second, second + 5))
{
cout << first << " is less than " << second << endl;
}
else
{
cout << first << " is greater than " << second << endl;
}
if (lexicographical_compare(first, first + 5, second, second + 9, cmp))
{
cout << first << " is less than " << second << endl;
}
else
{
cout << first << " is greater than " << second << endl;
}
getchar();
return 0;
}
运行结果:
apple is greater than Applement
apple is less than Applement
备注:
'A’的ASCII码为:65
'a’的ASII码为: 97
'A’的字典顺序是排在’a’之前的
lexicographical_compare是否只能比较字母呢?答案是肯定的,不是!
因为对于任意的可以使用opeartor<进行比较的对象都可以使用该函数!
一个简单的例子:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argv, char **argc)
{
vector<int> v1{ 1,2,3,4 };
vector<int> v2{ 1,2,3,4,5 };
vector<int> v3{ 1,2,3,3 };
cout << "v1=";
for (int i : v1)
cout << i << " ";
cout << endl;
cout << "v2=";
for (int i : v2)
cout << i << " ";
cout << endl;
cout << "v3=";
for (int i : v3)
cout << i << " ";
cout << endl;
if (lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end()))
cout << "v1 is less than v2 " << endl;
else
cout << "v2 is less than v1 " << endl;
if (lexicographical_compare(v1.begin(), v1.end(), v3.begin(), v3.end()))
cout << "v1 is less than v3 " << endl;
else
cout << "v3 is less than v1 " << endl;
getchar();
return 0;
}
运行结果:
v1=1 2 3 4
v2=1 2 3 4 5
v3=1 2 3 3
v1 is less than v2
v3 is less than v1
参考:
STL algorithm算法lexicographical_compare(30)
lexicographical_compare全部用法的中文帮助文档:
https://www.apiref.com/cpp-zh/cpp/algorithm/lexicographical_compare.html