您可以尝试让这两种类型都从包含该位置的基础继承,可能带有virtual Draw()
:
struct Base
{
Point pos;
virtual ~Base() {}
virtual void Draw() = 0;
};
struct Foo : base {};
struct Bar : base {};
std::list<Base*> list;
//...
list.sort([](Base *left, Base *right)
{
return left->pos.z < right->pos.z;
});
for(auto iter = list.begin(), end = list.end(); iter != end; ++iter)
{
(*iter)->Draw();
}
如果您想将列表分开,请在绘图之间交替,如果其中两个出现在一个之前Foo
,Bar
则将不起作用。Foo
Bar
但你的想法是正确的。您可以单独排序,然后在绘图时合并两个列表:
foo_list.sort();
bar_list.sort();
auto fiter = foo_list.begin(), fend = foo_list.end();
auto biter = bar_list.begin(), bend = bar_list.end();
while(fiter != fend && biter != bend)
{
// draw whichever Foo or Bar is closest, and increment only that iterator.
if((*fiter)->z_pos < (*biter)->z_pos)
{
(*fiter)->Draw();
++fiter;
}
else
{
(*biter)->Draw();
++biter;
}
}
// reached the end of one of the lists. flush out whatever's left of the other.
for(; fiter != fend; ++fiter)
{
(*fiter)->draw();
}
for(; biter != bend; ++biter)
{
(*biter)->draw();
}
如果您只想保留一个列表但有两种完全独立的类型,您也可以使用变体:
struct visitor
{
float operator()(Foo* f) const { return f->z_position; }
float operator()(Bar* b) const { return b->z_position; }
};
std::list<boost::variant<Foo*, Bar*>> list;
//...
list.sort([](boost::variant<Foo*, Bar*> const &left, boost::variant<Foo*, Bar*> const &right)
{
return apply_visitor(visitor(), left) < apply_visitor(visitor(), right);
});
for(auto iter = list.begin(), end = list.end(); iter != end; ++iter)
{
(*iter)->Draw();
}