std::lexicographical_compare
来自cppreference.com
| 在标头 <algorithm> 定义
|
||
| (1) | (C++20 起为 constexpr) |
|
| |
(2) | (C++17 起) |
| (3) | (C++20 起为 constexpr) |
|
| |
(4) | (C++17 起) |
检查第一个范围 [first1, last1) 是否按字典序小于 第二个范围 [first2, last2)。
1) 用
operator< 比较元素。3) 用给定的二元比较函数
comp 比较元素。2,4) 同 (1,3),但按照
policy 执行。这些重载只有在满足以下所有条件时才会参与重载决议:
|
|
(C++20 前) |
|
|
(C++20 起) |
字典序比较是拥有下列属性的运算:
- 逐元素比较两个范围。
- 首个不匹配元素定义一个范围是否按字典序小于 或大于 另一个。
- 如果一个范围是另一个的前缀,那么较短的范围小于 另一个。
- 如果两个范围拥有等价元素和相同长度,那么两个范围按字典序相等。
- 空范围按字典序小于 任何非空范围。
- 两个空范围按字典序相等。
参数
| first1, last1 | - | 要检验的第一个元素范围的迭代器对 |
| first2, last2 | - | 要检验的第二个元素范围的迭代器对 |
| policy | - | 所用的执行策略 |
| comp | - | 比较函数对象(即满足比较 (Compare) 要求的对象),如果首个实参小于 第二个,则返回 true。比较函数的签名应等价于如下:
虽然签名不必有 |
| 类型要求 | ||
-InputIt1, InputIt2 必须满足老式输入迭代器 (LegacyInputIterator) 。
| ||
-ForwardIt1, ForwardIt2 必须满足老式向前迭代器 (LegacyForwardIterator) 。
| ||
-Compare 必须满足比较 (Compare) 。
| ||
返回值
第一范围按字典序小于 第二个时返回 true,否则返回 false。
复杂度
给定 N1 为 std::distance(first1, last1),N2 为 std::distance(first2, last2):
1,2) 最多应用 2min(N1,N2) 次
operator< 进行比较。3,4) 最多应用 2min(N1,N2) 次比较函数
comp。异常
拥有名为 ExecutionPolicy 的模板形参的重载按下列方式报告错误:
- 如果作为算法一部分调用的函数的执行抛出异常,且
ExecutionPolicy是标准策略之一,那么调用 std::terminate。对于任何其他ExecutionPolicy,行为由实现定义。 - 如果算法无法分配内存,那么抛出 std::bad_alloc。
可能的实现
| lexicographical_compare (1) |
|---|
template<class InputIt1, class InputIt2>
bool lexicographical_compare(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2)
{
for (; (first1 != last1) && (first2 != last2); ++first1, (void) ++first2)
{
if (*first1 < *first2)
return true;
if (*first2 < *first1)
return false;
}
return (first1 == last1) && (first2 != last2);
}
|
| lexicographical_compare (3) |
template<class InputIt1, class InputIt2, class Compare>
bool lexicographical_compare(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2, Compare comp)
{
for (; (first1 != last1) && (first2 != last2); ++first1, (void) ++first2)
{
if (comp(*first1, *first2))
return true;
if (comp(*first2, *first1))
return false;
}
return (first1 == last1) && (first2 != last2);
}
|
示例
运行此代码
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>
void print(std::vector<char> const& v, auto suffix)
{
for (char c : v)
std::cout << c << ' ';
std::cout << suffix;
}
int main()
{
std::vector<char> v1{'a', 'b', 'c', 'd'};
std::vector<char> v2{'a', 'b', 'c', 'd'};
for (std::mt19937 g{std::random_device{}()};
!std::lexicographical_compare(v1.begin(), v1.end(),
v2.begin(), v2.end());)
{
print(v1, ">= ");
print(v2, '\n');
std::shuffle(v1.begin(), v1.end(), g);
std::shuffle(v2.begin(), v2.end(), g);
}
print(v1, "< ");
print(v2, '\n');
}
可能的输出:
a b c d >= a b c d
d a b c >= c b d a
b d a c >= a d c b
a c d b < c d a b
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 142 | C++98 | 最多只能进行 min(N1,N2) 次比较,但实际上无法实现(需要两次比较才能确定等价) | 比较次数上限翻倍 |
| LWG 1205 | C++98 | 涉及空范围的字典序比较的结果不明确 | 使之明确 |
