在C ++中使用自定义比较函数初始化多重集 [英] Initializing multiset with custom comparison function in C++
问题描述
考虑以下比较函数:
bool compare(std::shared_ptr<myObject> &lhs, std::shared_ptr<myObject> &rhs){
return lhs->value < rhs->value;
}
现在的想法是初始化一个多集的类型 std :: shared_ptr< myObject>
,它使用上述函数对元素进行排序。所以从书我读的应该这样做:
Now idea is to initialize a multiset of type std::shared_ptr<myObject>
which orders elements with above function. So from book i read it should be done like this:
std::multiset<std::shared_ptr<myObject>, decltype(compare)*> myset{compare};
问题:
我的问题是,在声明我undersad一个函数指针被传递来引用比较函数,但为什么我们initiazling set wtih {compare} ??它的重要性是什么,为什么有必要这样做呢?
My question is, in the declaration i understad a function pointer is passed to refer to compare function, but why are we initiazling the set wtih {compare}?? what is its importance and why is it necessary to do so like this??
推荐答案
因为集合需要一个比较函子与。如果你不指定一个,它将使用一个默认构造的。在这种情况下,由于你使用的是函数指针类型,默认构造的将是一个空指针,不能被调用;因此,您必须在运行时提供正确的函数指针。
Because the set needs a comparison functor to work with. If you don't specify one, it will make a default-constructed one. In this case, since you're using a function-pointer type, the default-constructed one will be a null pointer, which can't be called; so instead, you have to provide the correct function pointer at run time.
更好的方法是使用函数类类型(a.k.a. functor类型)。那么可以在编译时解析函数调用,并且默认构造的对象将做正确的事情:
A better approach might be to use a function class type (a.k.a. functor type); then the function call can be resolved at compile time, and a default-constructed object will do the right thing:
struct compare {
bool operator()(std::shared_ptr<myObject> &lhs,
std::shared_ptr<myObject> &rhs) const {
return lhs->value < rhs->value;
}
};
std::multiset<std::shared_ptr<myObject>, compare> myset;
这篇关于在C ++中使用自定义比较函数初始化多重集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!