我知道堆如何工作以及它如何安排最小和最大元素.如果vector只包含int,则很容易在STL中应用make_heap.但是make_heap()如果vector包含string和int的结构,如何应用.我希望根据int结构中的值来制作堆.请告诉我该怎么做.
您必须为您的结构提供比较功能:
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());
Run Code Online (Sandbox Code Playgroud)
是的,您可以直接使用std::make_heap,std::pair<int, std::string>因为std::pair具有所需的低于比较operator<.在上面链接的引用中甚至有一个例子,使用了特定的实例化std::pair.
| 归档时间: |
|
| 查看次数: |
7876 次 |
| 最近记录: |