erase() woes on std::multiset with custom Compare
Hello all,
I had a container of pointers to base. They were in a std::set<Base*>.
N.B. set was preferred over vector so iterators were not invalidated
when iterating.
Now I've been asked to order some of them by their runtime type.
Pointers to derived StyleLine should appear first. I tried std::set
with a comparison object but that only allows one object of each type
to be added (even though the pointer values are distinct). So, here I
am with std::multiset<Base*>. Seems to be going ok, but if I erase an
object of a particular type, all objects of that type are removed!
That was unexpected.
Here's an stripped down working example:
#include <iostream>
#include <set>
struct Base
{
virtual ~Base() {}
};
struct StyleLine : public Base
{
};
struct Piece : public Base
{
};
struct StyleLineFirstOrderer
{
bool operator()(const Base* a,const Base* b) const
{
const type_info& typeA = typeid(*a);
const type_info& typeB = typeid(*b);
if(typeA == typeB)
return false;
else
return typeA == typeid(StyleLine) != 0;
}
};
int main()
{
typedef std::multiset<Base*,StyleLineFirstOrderer> ContainerType;
ContainerType objects;
objects.insert(new Piece());
objects.insert(new Piece());
objects.insert(new Piece());
objects.insert(new Piece());
objects.insert(new Piece());
objects.insert(new Piece());
objects.insert(new StyleLine());
objects.insert(new StyleLine());
objects.insert(new StyleLine());
objects.insert(new StyleLine());
objects.insert(new StyleLine());
objects.insert(new StyleLine());
objects.erase(new Piece());
for(ContainerType::iterator it = objects.begin(); it !=
objects.end(); ++it)
std::cout << typeid(**it).name() << std::endl;
}
As you see, I try to erase a pointer to a piece at the end and it will
remove ALL the piece objects which is not what I want. I just want
erase to work on the value of the pointer.
Can someone give me some suggestions?
Thanks,
Pete