populate a map c++
To populate a map in C++, you can use the insert
function to add key-value pairs to the map. Here's an example:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap.insert(std::make_pair(1, "apple"));
myMap.insert(std::make_pair(2, "banana"));
myMap.insert(std::make_pair(3, "orange"));
// Print the map
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
return 0;
}
This code creates a std::map
called myMap
with integer keys and string values. The insert
function is then used to add key-value pairs to the map. In this example, the keys 1, 2, and 3 are associated with the values "apple", "banana", and "orange" respectively.
The map is then printed using a range-based for loop, which iterates over each key-value pair in the map and prints them out.
When you run this code, the output will be:
Key: 1, Value: apple
Key: 2, Value: banana
Key: 3, Value: orange
This demonstrates how to populate a map in C++ using the insert
function.