In C++, the map and multimap container classes are used to store key-value pairs,
where the keys are unique in a map and can be non-unique in a multimap. Both classes
are implemented as balanced binary search trees and provide logarithmic time
complexity for most operations, such as searching, inserting, and deleting elements.
A map object is created by including the <map> header file and declaring a variable
of type map<Key, Value>, where Key and Value are the types of the keys and values,
respectively. For example:
Copy code
#include <map>
std::map<std::string, int> myMap;
A multimap object is created similarly, but using the multimap class and including
the <map> header file.
Copy code
#include <map>
std::multimap<std::string, int> myMap;
Both classes have similar function such as insert, find, erase, etc.
To access the elements in the map, you can use the array subscript operator ([]) or
the at() member function. The insert() member function can be used to insert new
elements, and the erase() member function can be used to remove elements.
Please let me know if you have any more questions.
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> myMap;
// Insert elements
myMap["apple"] = 5;
myMap["banana"] = 3;
myMap["orange"] = 2;
// Print elements
std::cout << "Fruit: " << "Quantity" << std::endl;
for (const auto &p : myMap) {
std::cout << p.first << ": " << p.second << std::endl;
}
// Update an element
myMap["banana"] = 4;
// Print updated elements
std::cout << "Fruit: " << "Quantity" << std::endl;
for (const auto &p : myMap) {
std::cout << p.first << ": " << p.second << std::endl;
}
// Remove an element
myMap.erase("orange");
// Print remaining elements
std::cout << "Fruit: " << "Quantity" << std::endl;
for (const auto &p : myMap) {
std::cout << p.first << ": " << p.second << std::endl;
}
return 0;
}
This program creates a map object called myMap that stores string keys
(the names of fruits) and integer values (the quantities of each fruit). The
program then inserts three elements into the map, prints the elements, updates the
quantity of one of the fruits, removes another fruit, and finally prints the
remaining elements in the map.
You can use a similar approach to use a multimap, the only difference is that you
have to use the multimap class instead of map class.
Please let me know if you have any more questions or if there's anything else I can
help you with.
To embed this project on your website, copy the following code and paste it into your website's HTML: