有什么办法让std :: unordered_set <base /> :: count(Derived c)?

时间:2012-01-01 03:00:30

标签: c++

假设我有一个抽象基类和一个具有一些独特功能的派生类:

class Shape
{
    public:
    Shape();
};

class Circle : public Shape
{
    public:
    Circle(int radius) : radius(radius);
    int getRadius() { return this->radius; };
    private:
    int radius;
};

现在我可以将Circle *:s放在std :: vector中,然后检查vector是否有Shape *

std::vector< Circle* > v;

Circle* circle = new Circle(1);

v.push_back(circle);

// ...

Shape* someShape = ...; // I know it's a Circle but the pointer comes from class that only knows about Shapes

for(std::vector< Circle* >::iterator it = v.begin(); it != v.end(); ++it)
{
    Circle* c = *it;
    if((Shape)c == someShape)
    {
        // found
    }
}

// ...

delete c;

但我想使用std :: unordered_set(也适用于std :: unordered_map,std :: set,std :: map)因为它具有比线性更快的find()和count()

std::unordered_set< Circle* > u;

Circle* circle = new Circle(1);

u.insert(circle);

// ...

Shape* someShape = ...; // I know it's a Circle but the pointer comes from class that only knows about Shapes

if(u.count(someShape) == 1)
{
    // found
}

由于只存在std :: unordered_set&lt;而不是显而易见的我获得“未定义的函数”。键&gt; :: count(Key&amp; k);

有没有办法可以使用基类从std :: unordered_set中找到()或count()?

1 个答案:

答案 0 :(得分:1)

如果您知道它是一个圆圈,那么您只需将someShape投射到Circle *并将其传递给find()

Shape* someShape = ...; // I know it's a Circle but the pointer comes from class that only knows about Shapes
Circle* someCircle = dynamic_cast<Circle*>(someShape);

if (someCircle != NULL && u.count(someCircle) == 1)
{
    // found 
}