Click to See Complete Forum and Search --> : heap usage


lazlo
December 10th, 2002, 10:22 PM
Greetings
I was wondering if someone could could help me out with a problem concerning heaps. I have a vector of a struct that contains a string and a int i.e.
typedef struct wordusage
{
string word;
int num;
};
I want to create a heap based on the integer so I can easily find the largest "num"s in the vector. make_heap of course won't operate on my struct, so how can I heap the int without losing its corresponding string?

Philip Nicoletti
December 10th, 2002, 10:53 PM
Why won't make_heap() work on your struct ?


#include <algorithm>
#include <string>
#include <vector>
#include <iostream>

using namespace std;

struct wordusage
{
string word;
int num;
};

struct sort_function
{
inline bool operator () (const wordusage & lhs , const wordusage & rhs)
{
return lhs.num < rhs.num;
}
};

int main()
{
vector<wordusage> v;

wordusage w1;
w1.word ="hello";
w1.num = 2;
v.push_back(w1);

wordusage w2;
w2.word ="world";
w2.num = 5;
v.push_back(w2);

wordusage w3;
w3.word ="and";
w3.num = 10;
v.push_back(w3);

wordusage w4;
w4.word ="zebra";
w4.num = 1;
v.push_back(w4);

wordusage w5;
w5.word ="red";
w5.num = 3;
v.push_back(w5);

make_heap(v.begin(),v.end(),sort_function());

vector<wordusage>::iterator i;
for (i=v.begin(); i!=v.end(); ++i)
{
cout << (*i).num << " " << (*i).word << endl;
}

return 0;
}

lazlo
December 10th, 2002, 11:08 PM
Silly me, I forgot to include a sort method. Thanks for the input!