I'd like to create a map with an int and my own custom class. Is there a way to do this?
map<int, MyClass> myMap;
If not, how do I go about accomplishing this? Basically, I want an id(or preferably an enum
) to point to my own custom class. In most other languages, this would be a simple hash.
Specify the type of the pointer to your comparison function as the 3rd type into the map, and provide the function pointer to the map constructor: map<keyType, valueType, typeOfPointerToFunction> mapName(pointerToComparisonFunction);
We can use any of the data types as the data type of the key of the map. Even a user-defined data type can be used as key data type.
map insert() in C++ STLThe map::insert() is a built-in function in C++ STL which is used to insert elements with a particular key in the map container. Parameters: The function accepts a pair that consists of a key and element which is to be inserted into the map container.
Maps are part of the C++ STL (Standard Template Library). Maps are the associative containers that store sorted key-value pair, in which each key is unique and it can be inserted or deleted but cannot be altered. Values associated with keys can be changed.
#include <map>
std::map<int, MyClass> myMap;
MyClass foo;
myMap[5] = foo;
myMap[5].bar = 10;
You do need MyClass
to be default- and copy- constructible, so it can be created (if you use, e.g., myMap[5]
) and copied into the map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With