lezebulon
lezebulon

Reputation: 7994

Why does map::find need my parameter to not be const?

std::map<Item*, item_quantity_t> _items;

bool Inventory::hasItem(Item const& item) {

    return (_items.find(&item) != _items.end() );

};

This code won't work, but changing the input type of "hasItem" to Item & item will work... can someone explain why to me? I've seen that std::find takes a const reference, so passing it a const object should be ok, at least it's what I understand

Upvotes: 1

Views: 180

Answers (5)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

std::map<Key, Value>::find() doesn't care about the argument passed being const. However, you seem to care deeply about you key type being a non-const pointer to Item which you won't get from taking the address of a Item const&. That said, I doubt that you really want to use pointers as the key to you map.

Upvotes: 0

ruakh
ruakh

Reputation: 183341

std::find takes a const reference

This is true, but all it means is that the method won't modify the Item *. In order to pass in a const Item * (which is what &item is), you'd need a guarantee that the method won't modify the underlying Item. That guarantee does actually exist, but C++ can't tell that. So you'd have to write:

_items.find(const_cast<Item *>(&item))

to inform C++ that you know this is safe.

Upvotes: 2

CygnusX1
CygnusX1

Reputation: 21778

It would work if your map was over a pointers to const items:

std::map<const Item*, item_quantity_t> _items;

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254471

Since you've defined the map to contain non-const pointers, that's the type you'll need to call find, and you can't get one of those from a const reference. You could change the key type to a const pointer:

std::map<Item const *, item_quantity_t> _items;

Upvotes: 0

Rob Kennedy
Rob Kennedy

Reputation: 163287

You've defined that the key type for your map is a pointer to a non-const Item, Item*. The find method expects a (const reference to a) value of the key type, so it requires a pointer to non-const.

When you expand the templates, the parameter type of find is Item* const&.

You can either change your hasItem to take a non-const reference Item&, or you can change your key type to be a pointer to a const Item Item const*.

Upvotes: 3

Related Questions