一:功能
按字典顺序比较两个序列,判断第一个序列是否小于(或大于)第二个序列
二:用法
#include <compare>
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <format>int main() {// for demonstration only, prefer std::arrayint x[] = {1, 2, 3};int y[] = {1, 4};bool cmp1 = std::lexicographical_compare(&x[0], &x[3], &y[0], &y[2]);// cmp1 == true,1>=1, 2>=2, 3>=3std::format_to(std::ostreambuf_iterator(std::cout),"cmp1 == {}\n", cmp1);std::vector<std::string> names1{"Zod", "Celeste"};std::vector<std::string> names2{"Adam", "Maria"};bool cmp2 = std::ranges::lexicographical_compare(names1, names2, [](const std::string& left, const std::string& right) {return left.length() < right.length();});//len("Celeste") > len("Zod") std::format_to(std::ostreambuf_iterator(std::cout),"cmp2 == {}\n", cmp2);// different thanbool cmp3 = names1 < names2; // Zod > Adamstd::format_to(std::ostreambuf_iterator(std::cout),"cmp3 == {}\n", cmp3);
}
三:实现
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>template<class InputIt1, class InputIt2>
bool my_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);
}void print(const std::vector<char>& 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'};//比较v1, v2,如果v1 < v2 退出循环,每次循环随机 shuffle v1 和v2for (std::mt19937 g{std::random_device{}()};!my_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');
}