gpt4 book ai didi

c++ - 有什么方法可以让 std::unordered_set::count(Derived c)?

转载 作者:行者123 更新时间:2023-11-28 08:12:22 31 4
gpt4 key购买 nike

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

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< Key >::count(Key& k);

有什么方法可以使用基类从 std::unordered_set 中找到 () 或 count() 吗?

最佳答案

如果您知道它是一个圆圈,那么您可以简单地将 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
}

关于c++ - 有什么方法可以让 std::unordered_set<Base>::count(Derived c)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8691629/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com