0

I'm trying here to use a class Bar that stores a ordered array of Foo, by it's member var as seen bellow.

I was expecting the output of this like 3,4,5 but I get 5,3,4.

I'm using my own compare function (mandatory because my Foo struct has more data) and after pushing back to the vector, I push the vector back to the heap and re-order it.

What am I missing here?

What I want is to push a Foo object into my queue, and re-order automatically.

struct Foo
{
    int var;
    //etc.
};

struct compare
{
   bool operator()(const Foo& s1, const Foo& s2)
   {
       return s1.var < s2.var;
   }
};

class Bar
{
private:
    std::vector<Foo> m_vector;
public:
    Bar() 
    {
        std::make_heap(m_vector.begin(), m_vector.end(), compare());
    }

    ~Bar() {}

    void push (const Foo& t)
    {
        m_vector.push_back(t);
        std::push_heap(m_vector.begin(),m_vector.end(), Comp());
    }

    void pop()
    {
        m_vector.pop_back();
    }

    void dump(void)
    {
        printf ("\n Dumping:");
        for(int i = 0; i < m_vector.size() ; i++)
        {
            printf ("%d ", m_vector.at(i).var);
        }
        printf ("\n");
    }
};

int main() 
{
    Bar myBar;

    myBar.dump();

    Foo t1;
    t1.var = 3;

    myBar.push(t1); 
    myBar.dump();

    Foo t2;
    t2.var = 4;

    myBar.push(t2); 
    myBar.dump();

    Foo t3;
    t3.var = 5;

    myBar.push(t3); 
    myBar.dump();

    return 0;
}
waas1919
  • 2,365
  • 7
  • 44
  • 76

1 Answers1

2

If you are getting your objects in the reverse order, than you should switch the comparison signal:

bool operator()(const Foo& s1, const Foo& s2)
{
   return s1.var > s2.var;
}

However, it seems that you don't understand heaps properly. Heaps do not keep sorted objects, but rather only partially sorted. Notice that they will still pop objects in order, but you need to actually pop them, just iterating the heap will not do it.

Notice in the following picture that the array is not sorted at all. However, the heap does possess an important property when rendered as a tree: every node is smaller than all of its descendants. That's what partially sorted means. The objects are not sorted, but they are related to each other in a way which can be efficiently sorted.

enter image description here

To get your elements back sorted you need to pop them.

Edit: BTW, you should use std::pop_heap, not std::vector::pop_back. For reasons that should be clear after the previous explanation

André Fratelli
  • 5,920
  • 7
  • 46
  • 87