问题
I know how does heap work and how it arranges min and max elements. It is easy, if vector contains only int
, to apply make_heap in STL. But how to apply make_heap()
if vector contains structure of string and int. Iwant to make heap based on int
value in structure.
Please tell me how to do that.
回答1:
You have to provide comparison function for your structure:
struct A
{
int x, y;
};
struct Comp
{
bool operator()(const A& s1, const A& s2)
{
return s1.x < s2.x && s1.y == s2.y;
}
};
std::vector<A> vec;
std::make_heap(vec.begin(), vec.end(), Comp());
回答2:
Yes, you can use std::make_heap with std::pair<int, std::string>
directly because std::pair has the required less-than comparison operator<. There is even an example in the reference linked above using that particular instantiation of std::pair
.
来源:https://stackoverflow.com/questions/13190269/c-stl-make-heap-with-pairint-string-as-data-type