STL 中的 lexicographical_compare() 算法可以比较由开始和结束迭代器定义的两个序列。它的前两个参数定义了第一个序列,第 3 和第 4 个参数分别是第二个序列的开始和结束迭代器。
默认用 < 运算符来比较元素,但在需要时,也可以提供一个实现小于比较的函数对象作为可选的第 5 个参数。如果第一个序列的字典序小于第二个,这个算法会返回 true,否则返回 false。所以,返回 false 表明第一个序列大于或等于第二个序列。
序列是逐个元素比较的。第一对不同的对应元素决定了序列的顺序。如果序列的长度不同,而且短序列和长序列的初始元素序列匹配,那么短序列小于长序列。长度相同而且对应元素都相等的两个序列是相等的。空序列总是小于非空序列。
#include <algorithm>
template <class _InputIter1, class _InputIter2>
bool lexicographical_compare(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2)
template <class _InputIter1, class _InputIter2, class _Compare>
bool lexicographical_compare(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2,
_Compare __comp)
参数 | 描述 |
---|---|
__first1 | 输入迭代器 |
__last1 | 输入迭代器 |
__first2 | 输入迭代器 |
__last2 | 输入迭代器 |
__comp | 自定义比较规则 |
lexicographical_compare 算法会拿着 [Frist1,Last1) 中的值和 [first2,last2) 中的元素进行比较,并且返回第一个找到的两个区间中不匹配的值,并且返回。
使用 STL lexicographical_compare 函数比较集合
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
int main()
{
std::cout << "嗨客网(www.haicoder.net)\n" << std::endl;
std::vector<std::string> phrase1{"the", "tigers", "of", "wrath"};
std::vector<std::string> phrase2{"the", "horses", "of", "instruction"};
auto less = std::lexicographical_compare(std::begin(phrase1), std::end(phrase1), std::begin(phrase2), std::end(phrase2));
std::cout << (less ? "are":"are not") << " less than" << std::endl;
}
我们在 Linux 下使用 g++ 进行编译,具体命令如下:
g++ lexicographical_compare.cpp
编译后,我们直接运行生成的二进制文件 a.out
,如下图所示:
我们使用了 lexicographical_compare 函数,对集合进行了对比。
STL 中的 lexicographical_compare() 算法可以比较由开始和结束迭代器定义的两个序列。它的前两个参数定义了第一个序列,第 3 和第 4 个参数分别是第二个序列的开始和结束迭代器。