C++标准库提供std::equal_to.此函数对象默认调用operator==on类型T.
使用有什么好处std::equal_to?你能提供一个std::equal_to有用的例子吗?
Ser*_*eyA 38
用于算法.它提供了一个带有operator()的仿函数,因此可以一般地使用.
具体(和人为)的例子,如评论中所述:
// compare two sequences and produce a third one
// having true for positions where both sequences
// have equal elements
std::transform(seq1.begin(), seq1.end(), seq2.begin(),
std::inserter(resul), std::equal_to<>());
Run Code Online (Sandbox Code Playgroud)
不确定谁可能需要它,但这是一个例子.
Nik*_*lis 21
拥有std::equal_to非常有用,因为它允许将相等比较用作仿函数,这意味着它可以作为参数传递给模板和函数.这是使用相等运算符无法实现的,==因为运算符不能作为参数传递.
例如,考虑如何使用它std::inner_product, std::find_first_of和std::unordered_map.
它主要用作模板参数传递给算法.您不能将运算符指定为模板参数,但可以指定函数.典型用途如下:
template <class compare = std::equal_to<>, class T, class InIter>
bool contains(InIter begin, InIter end, T value, compare cmp={}) {
for (InIter p = begin; p != end; ++p)
if (cmp(*p, value))
return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)
如果您(例如)某种类型的结构包含多个字段,您可能需要一个比较函数,该函数仅比较指示身份的几个特定字段(例如人名),但忽略其他字段(例如其当前权重)在这种情况下,您将该比较函数作为模板参数传递,并且只能比较您关注的字段.
对于您正在处理的其他情况,比如搜索整数数组,您可以使用默认比较函数.
这些天来,事实并非如此.在lambdas之前,它可用作调用的函子形式==,用于标准算法调用.现在你只是写[](auto& x, auto& y) { return x == y; }.
| 归档时间: |
|
| 查看次数: |
6300 次 |
| 最近记录: |