CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: heap usage

  1. #1
    Join Date
    Dec 2002
    Posts
    2

    heap usage

    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?

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725
    Why won't make_heap() work on your struct ?

    Code:
    #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;
    }

  3. #3
    Join Date
    Dec 2002
    Posts
    2
    Silly me, I forgot to include a sort method. Thanks for the input!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured