看这个例子(来自cppreference):
#include <algorithm>
#include <vector>
#include <iostream>
struct S
{
int number;
char name;
// note: name is ignored by this comparison operator
bool operator< ( const S& s ) const { return number < s.number; }
};
int main()
{
// note: not ordered, only partitioned w.r.t. S defined below
const std::vector<S> vec = { {1,'A'}, {2,'B'}, {2,'C'}, {2,'D'}, {4,'G'}, {3,'F'} };
std::cout << "\n" "Using heterogeneous comparison: ";
struct Comp
{
bool operator() ( const S& s, int i ) const { return s.number < i; }
bool operator() ( int i, const S& s ) const { return i < s.number; }
};
const auto p2 = std::equal_range(vec.begin(),vec.end(), 2, Comp{});
for ( auto i = p2.first; i != p2.second; ++i )
std::cout << i->name << ' ';
}
如果我想在中使用结构,是否需要以如下两种方式重载运算符 () 以用于仿函数std::equal_range
?
PS:这是this one的后续问题equal_range如何利用异构比较?,显然其中一个问题太多了,因此我将其拆分为仅询问此处的两个重载。