【发布时间】:2018-06-08 13:34:32
【问题描述】:
我正在尝试提出一个 lambda,它允许 std::equal_range 返回一个范围,其中搜索的字符串作为前缀存在。由于这可能措辞不正确,举个例子:
给定字符串向量:
- C:\users\andy\documents\screenshot.jpg
- C:\users\bob\desktop\file.txt
- C:\users\bob\desktop\picture.png
- C:\users\bob\desktop\video.mp4
- C:\users\john\desktop\note.txt
我希望返回的迭代器是
- C:\users\bob\desktop\file.txt 和
- C:\users\bob\desktop\video.mp4.
我将如何为 std::equal_range 编写一个比较 lambda 来完成此任务,或者 std::equal_range 不是适合这项工作的工具?
【问题讨论】:
-
std::equal_range的四参数重载与比较可调用对象似乎足以完成任务。只需编写一个实现与前缀匹配的比较的比较对象。您必须仔细使用separate implementations ofcomp(element, value)andcomp(value, element)对比较对象进行编码,才能返回正确的比较结果。 -
这似乎可行,但我不确定它是否完全正确:ideone.com/NiV02v 您可以使用
std::string.compare避免使用substr,但这对我来说更清楚了。 耸耸肩 -
我会采用一种比 Retired Ninja 稍微复杂的方法。我会将前缀字符串强制转换为不是
std::string的独特辅助类型。那我就可以区分这两种比较函数了,在自定义比较器类中实现两个operator()s,比较prefix to string,prefix to string。 -
C:\users\bob\desktop\picture.png为什么不应该被退回呢? -
使用
<=或>=打破了严格的弱排序要求进行比较。这个答案比我能解释得更好。 :) stackoverflow.com/a/981299/920069