C++ STL--make_heap with pair<int,string> as data type

本秂侑毒 提交于 2019-12-21 05:18:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!