Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ STL map with a custom class as second type

Tags:

c++

map

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.

like image 988
Jayson Bailey Avatar asked Sep 25 '09 16:09

Jayson Bailey


People also ask

How do you use the comparator function on a map?

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);

Can we use any user defined data type as a key in map in C++?

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.

How do I insert a map in STL?

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.

How do you define a map in STL?

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.


1 Answers

#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.

like image 107
Jesse Beder Avatar answered Nov 06 '22 00:11

Jesse Beder