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.
Asked
Active
Viewed 9,601 times
4

username_4567
- 4,737
- 12
- 56
- 92
-
3What have you tried? In particular, did you try giving an explicit comparison function? – rici Nov 02 '12 at 06:17
-
I don't know how to do with comparison fun... – username_4567 Nov 02 '12 at 06:17
-
1It's been a while since I've looked, but doesn't `pair` come with an ordering that does what you want? – Nov 02 '12 at 06:25
-
1@Hurkyl The default ordering for `std::pair` is the lexicographic ordering. That implies that both elements of the pair are taken into account for the ordering, not only the first. For the heap the OP is about to build it may (perhaps) not matter, but for stable sort it would. – jogojapan Nov 02 '12 at 06:29
-
1You don't need your own comparison function. See my answer and links therein. – juanchopanza Nov 02 '12 at 07:05
2 Answers
9
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());

user541686
- 205,094
- 128
- 528
- 886

Denis Ermolin
- 5,530
- 6
- 27
- 44
-
-
-
I don't think there is any need for the comparison function, unless you want to specify your own logic. If you want lexicographical comparison, just use the default. – juanchopanza Nov 02 '12 at 06:50
7
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
.

juanchopanza
- 223,364
- 34
- 402
- 480