c++ - Invalid heap while pushing object into vector and then pushing vector into heap -


i'm trying here use class bar stores ordered array of foo, it's member var seen bellow.

i expecting output of 3,4,5 5,3,4.

i'm using own compare function (mandatory because foo struct has more data) , after pushing vector, push vector heap , re-order it.

what missing here?

what want push foo object queue, , 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 = 0; < 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; } 

if getting objects in reverse order, should switch comparison signal:

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

however, seems don't understand heaps properly. heaps not keep sorted objects, rather partially sorted. notice still pop objects in order, need pop them, iterating heap not it.

notice in following picture array not sorted @ all. however, heap possess important property when rendered tree: every node smaller of descendants. that's partially sorted means. objects not sorted, related each other in way can efficiently sorted.

enter image description here

to elements sorted need pop them.

edit: btw, should use std::pop_heap, not std::vector::pop_back. reasons should clear after previous explanation


Comments