A heap of structs

This is a discussion on A heap of structs within the C++ Programming forums, part of the General Programming Boards category; I have a vector of structs and I want to make it into a heap or priority queue. I've looked ...

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    1

    A heap of structs

    I have a vector of structs and I want to make it into a heap or priority queue.

    I've looked up examples of how this is done with integer arrays using both make_heap() and priority_queue<>, but how does one specify the ordering of a struct? It's no longer a simple matter of throwing in greater<int> or less<int> as the comparator argument.

    I suppose I could write my own comparator function, but what's the syntax when calling it in these cases?

    Any help/resources would be appreciated.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,805
    If you are using a function object for your comparator, you would instantiate that function object as you called make_heap. If you are just using a function, then you would pass it as a function pointer:
    Code:
    make_heap(container.begin(), container.end(), Comparator()); // Function object
    make_heap(container.begin(), container.end(), comparator);   // Function pointer
    Another way is to overload operator< for your class (struct).
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. heap
    By George2 in forum Windows Programming
    Replies: 2
    Last Post: 11-10-2007, 10:49 PM
  2. Heap Work
    By AndyBomstad in forum C++ Programming
    Replies: 1
    Last Post: 05-16-2005, 12:09 PM
  3. Do you know...
    By davejigsaw in forum C++ Programming
    Replies: 1
    Last Post: 05-10-2005, 10:33 AM
  4. heap question
    By mackol in forum C Programming
    Replies: 1
    Last Post: 11-30-2002, 04:03 AM
  5. Searching structs...
    By Sebastiani in forum C Programming
    Replies: 1
    Last Post: 08-25-2001, 12:38 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21