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;
}