CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 2 of 2 FirstFirst 12
Results 16 to 17 of 17
  1. #16
    Join Date
    Jun 2012
    Posts
    8

    Re: Array to Heap Tree

    Something like this:
    Code:

    #include <algorithm>

    int main()
    {
    const int capacity = 11;
    int a[capacity] = {1, 2, 3, 4, 5, 6, 7};
    int size = 7;
    std::make_heap(a, a + size);

    // Add 50 to the heap:
    a[size++] = 50;
    std:ush_heap(a, a + size);

    return 0;
    }
    hmm why did you do "a+size" ?


    How about this? does it seem right?

    Code:
     #include <iostream>
        #include <algorithm>
    
        void heap_sort(int* begin, int* end)
        {
        std::make_heap(begin, end);
        std::sort_heap(begin, end);
        }
    
        int main ()
        {
          const int n = 11;   
          int a[n] = {1, 2, 3, 4, 5, 6, 7};
          int size = 7;
        
        heap_sort( &a[0], &a[size]);
    
        // Add 50 to the heap:
        a[size++] = 50;
        std::push_heap(&a[size], &a[n]);
    
    
        return 0;
        }
    thanks a lot for responding

  2. #17
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Array to Heap Tree

    Quote Originally Posted by R1111
    hmm why did you do "a+size" ?
    It is a simpler way of writing &a[size].

    Quote Originally Posted by R1111
    How about this? does it seem right?
    It is wrong. Once you do sort_heap, the range is no longer a heap, so you cannot subsequently call push_heap with it. Furthermore, the first argument to push_heap should be a pointer to the first element in the array. The second argument... well, I already said this before. You need to think carefully about what the arguments to push_heap should be.

    Actually, why don't you pause for a moment and use std::sort instead? Get familiar with how to use std::sort. This knowledge will help you understand how to use std::make_heap and std::push_heap, but very importantly, you can easily check if you are using std::sort correctly by printing the part of the array that is in use since it is far easier to check if a range is correctly sorted than to check if a range is a heap.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Page 2 of 2 FirstFirst 12

Tags for this Thread

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