当前位置: 首页 > news >正文

C++ STL std::lexicographical_compare用法和实现

一:功能

       按字典顺序比较两个序列,判断第一个序列是否小于(或大于)第二个序列

二:用法

#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');
}

http://www.lryc.cn/news/398470.html

相关文章:

  • ORM Bee,如何使用Oracle的TO_DATE函数?
  • HTML CSS 基础复习笔记 - 框架、装饰、弹性盒子
  • C++:创建线程
  • python如何查看类的函数
  • P6. 对局列表和排行榜功能
  • uniapp easycom组件冲突
  • 总结24个Python接单赚钱平台与详细教程,兼职月入5000+
  • macOS 的电源适配器设置
  • 视觉SLAM与定位之一前端特征点及匹配
  • 开源项目的认识理解
  • 37.哀家要长脑子了!--层序遍历
  • 【从零开始AI绘画6】StableDiffusionWebUI拓展的安装方法以及推荐的几个拓展
  • HTML5表单的自动验证、取消验证、自定义错误信息
  • SpringMVC系列九: 数据格式化与验证及国际化
  • 判断链表中是否有环(力扣141.环形链表)
  • Kubernetes基于helm部署jenkins
  • 【Linux】vim详解
  • Android11 mtk 第二次设置壁纸,锁屏壁纸不变的问题
  • Java学习路线
  • java 实现人脸检测
  • VSCode神仙插件——Codeium (AI编程助手)
  • css文本划线效果(text-decoration相关属性详解)
  • 《Windows API每日一练》8.5 listbox控件
  • 使用Node.js 框架( Express.js)来创建一个简单的 API 端点
  • 企业服务行业CRM解决方案
  • 服务器怎么进PE系统?
  • Linux内核编译与调试menuos-linux-3.18.6-在ubuntu20.04环境
  • java-mysql 三层架构
  • 打工人如何应对AI对工作岗位的风险
  • C++:从C语言过渡到C++