Suppose I create a user defined variable in C++. How can I use that variable as a value in a map?
For example:
std::map<int, mytype> mappa;
If I could get some simple examples, so that I could understand the concept fully, that'd be great.
Suppose I create a user defined variable in C++. How can I use that variable as a value in a map?
For example:
std::map<int, mytype> mappa;
If I could get some simple examples, so that I could understand the concept fully, that'd be great.
Here is a small example:
#include <iostream>
#include <map>
class MyClass
{
// Upto you how your class looks like
};
int main()
{
// A map where key = int and value = MyClass
std::map<int, MyClass> myMap;
// Have some objects of MyClass to demonstrate the use of myMap
MyClass obj1, obj2, obj3;
/* Some basic operations */
// Example of insertion
myMap.insert({12, obj1});
myMap.insert({13, obj2});
myMap.insert({22, obj3});
// Example of deletion
myMap.erase(22); // removes myMap[22] i.e. obj3 leaves the map
// Example of searching
if (myMap.find(22) != myMap.end())
{
// process myMap[22]
std::cout << "myMap[22] exists";
}
else
{
std::cout << "myMap[22] does not exist";
}
// ...
return 0;
}
Basically, there's nothing much difficult to use a user-defined type as values in a map. If you meant to use them as keys then you can look at this post.
You can also look at this documentation to learn more of its functions.