algorithm::lexicographical_compare()
描述 (Description)
C ++函数std::algorithm::lexicographical_compare()测试一个范围是否按字典顺序小于另一个范围。 词典比较是通常用于在词典中按字母顺序对单词进行排序的比较。
声明 (Declaration)
以下是std :: algorithm :: lexicographical_compare()函数形式std :: algorithm头的声明。
C++98
template <class InputIterator1, class InputIterator2, class Compare>
bool lexicographical_compare(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,Compare comp);
参数 (Parameters)
first1 - 将迭代器输入到第一个序列的初始位置。
last1 - 将迭代器输入到第一个序列的最终位置。
first2 - 将迭代器输入到第二个序列的初始位置。
last2 - 将迭代器输入到第二个序列的最终位置。
comp - 一个二进制函数,它接受两个参数并返回bool。
返回值
如果一个范围按字典顺序小于秒,则返回true,否则返回false。
异常 (Exceptions)
如果二元函数或迭代器上的操作抛出异常,则抛出异常。
请注意,无效参数会导致未定义的行为。
时间复杂
2 * min(N1,N2)其中N1 = std :: distance(first1,last1)和N2 = std :: distance(first2,last2)。
例子 (Example)
以下示例显示了std :: algorithm :: lexicographical_compare()函数的用法。
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
bool ignore_case(string s1, string s2) {
return true;
}
int main(void) {
vector<string> v1 = {"one", "two"};
vector<string> v2 = {"One", "Two", "Three"};
bool result;
result = lexicographical_compare(v1.begin(), v1.end(),
v2.begin(), v2.end());
if (result == false)
cout << "v1 is not less than v2." << endl;
result = lexicographical_compare(v1.begin(), v1.end(),
v2.begin(), v2.end(), ignore_case);
if (result == true)
cout << "v1 is less than v2." << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 -
v1 is not less than v2.
v1 is less than v2.