Hichigaya Hachiman
Hichigaya Hachiman

Reputation: 307

Find derived objects in a container

Let's say I have base class Thing and from that I have Shoes, Pants, Shirt. Then I have a vector<Thing*> closet.

How would I find how many Shirt do I have in my closet?

Upvotes: 0

Views: 35

Answers (1)

cdhowie
cdhowie

Reputation: 169008

Use std::count_if with a lambda that uses a dynamic downcast to determine if each element points to a Shirt (or a subtype thereof -- this would also catch, say, TShirt objects where TShirt is a class that inherits Shirt):

auto shirts = std::count_if(
    std::begin(closet),
    std::end(closet),
    [] (Thing const *thing) {
        return dynamic_cast<Shirt const *>(thing) != nullptr;
    }
);

Upvotes: 5

Related Questions