Why map :: find need my parameter to not be const?
source link: https://www.codesd.com/item/why-map-find-need-my-parameter-to-not-be-const.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Why 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
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*
.
Related Articles
in grep, why does he need to escape [while not for]
Why does Munmap need a parameter as a parameter?
Why is ClassManifest needed with Array but not List?
Why have the variad model parameter packs not been extended?
why `tasklist | find & ldquo; cmd.exe & rdquo; `not working on win7 but xp and vista?
Why Map a loadFactor and List does not have it?
Why the window.location.href parameter does not remove script execution
Why do I need a reinterpret_cast to convert Fred ** const to void ** const?
C ++: Any reason why the function returning the pointer should not be const?
Why do I need a finalizer if my class implements IDisposable?
Why do we need to delete the allocated memory in the C ++ assignment operator?
Why do we need to specify the size of the column when passing a 2D array as a parameter?
Why do we need a generic here? Is the protocol not enough?
Why do we need & ldquo; map & rdquo; be part of MapReduce?
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK