[英]C++ set<struct>
I am solving a problem and need a custom set with special functions. 我正在解决一个问题,需要具有特殊功能的自定义设置。 The problem is I don't know how to implement them. 问题是我不知道如何实现它们。
struct S
{
int x;
int freq;
S(int X, int F)
{
x = X, freq = F;
}
};
bool compare(const S &a, const S &b)
{
if (a.freq != b.freq) return a.freq > b.freq;
return a.x < b.x;
}
int main()
{
std::set<S> my_set; //custom compare
my_set.find(S(10, 11)); //find first element with x = 10
my_set.insert(S(20, 30)); //normal insertion
my_set.erase(S(20, 30)); //erase element with x = 20 && freq = 30
cout << my_set.size() << endl;
}
The second template argument to std::set
is a custom comparator functor: std::set
的第二个模板参数是自定义比较器函子:
std::set<S, compare> my_set; //custom compare
To make this work, your comparator needs to be a type that implements operator()
(the function call operator), which can be a simple struct like this: 为了使此工作有效,您的比较器必须是实现operator()
(函数调用运算符)的类型,它可以是一个简单的结构,如下所示:
struct compare {
bool operator()(const S &a, const S &b)
{
if (a.freq != b.freq) return a.freq > b.freq;
return a.x < b.x;
}
};
std::set<S>
by default uses std::less<S>
, and you are allowed to specialize that: std::set<S>
默认使用std::less<S>
和你被允许专门指出:
namespace std {
template <> struct less {
bool operator()(const S &a, const S &b) { return compare(a,b); }
};
}
(Or use a custom comparator, see Thomas' answer) (或使用自定义比较器,请参见Thomas的答案)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.