c++ - 为什么 std::inlcudes 在条件中使用小于运算符而不是相等运算符?
问题描述
std::includes
我有来自https://en.cppreference.com/w/cpp/algorithm/includes的算法实现
template<class InputIt1, class InputIt2>
bool includes(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2)
{
for (; first2 != last2; ++first1)
{
if (first1 == last1 || *first2 < *first1)
return false;
if ( !(*first1 < *first2) )
++first2;
}
return true;
}
它工作得很好但是我想知道为什么在
if statement
循环内的第二个中使用小于运算符<
而不是相等运算符==
?这是我的类似实现:
template<class InputIt1, class InputIt2> bool including(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2){ while (first2 != last2){ if (first1 == last1 || *first2 < *first1) return false; if ( *first1 == *first2 ) ++first2; ++first1; } return true; } int main(){ std::vector<int> v{1, 5, 7, 23, 24, 57, 77}; // std::sort(v.begin(), v.end()); int a[]{7, 24}; std::cout << including(v.begin(), v.end(), a, a + 2) << '\n'; // 1 std::cout << std::includes(v.begin(), v.end(), a, a + 2) << '\n'; // 1 }
所以我得出了这样的结论:
第一个条件:
*first2 < *first1
-> 返回 false。第二个条件:
!(*first1 < *firs2)
->*first1 >= *first2
所以*first1 > *first2
导致算法返回false
并*first1 >= *first2
导致firsts2
递增,所以唯一递增的条件first2
是什么时候*first1 == *first2
那么为什么使用小于<
和否定运算符运算符而不是像我的实现中那样!
直接使用等于运算符呢?==
- 这仅仅是为了某种可读性和兼容性吗?
- 我的分析正确吗?谢谢!
解决方案
该算法正在排序范围内工作。您需要一个<
关系来对一系列元素进行排序,但不一定是一个==
关系,因此使用<
构成的限制更少并且更通用。
还要考虑大多数算法和容器使用<
而不是==
比较元素。参见例如std::map
:
在标准库使用比较要求的任何地方,唯一性都是通过使用等价关系确定的。用不精确的术语来说,如果两个对象 a 和 b 的比较都小于另一个:!comp(a, b) && !comp(b, a),则认为两个对象是等价的(不唯一的)。
映射中的两个键在!comp(a,b) && !comp(b,a)
. 大多数情况下,这与 相同a == b
,但不一定。
推荐阅读
- excel - 如何以编程方式隐藏/删除图表中的类别?
- android - TextInputLayout 隐藏文本
- c# - Excel DNA IntelliSense 突然停止工作
- html - HTML CSS 表格设计指南
- python - 希望合并 2 个条形图
- node.js - 使本地网络之外的计算机可以使用 create-react-app
- .net - 有没有办法使用 .NET SPARK 更改导出文件名?
- sublimetext3 - Sublime Text 插件开发:修改快速面板添加自定义文本标题或标签?
- ios - 通过 Swift 在 iPhone (iOS) 开发中存储/检索用户数据(读/写文件)的正确方法是什么?
- excel - Openxlsx loadWorkbook 不返回工作簿对象