how to insert in unordered map of string and vector<string in cpp
- User
how to insert in unordered map of string and vector<string in cpp
- Assistant
In C++, you can use the
std::unordered_mapto create a map where the keys are of typestd::stringand the values are of typestd::vector<std::string>. To insert elements into this unordered map, you can use theinsertmethod or the subscript operator ([]).Here's an example demonstrating both methods:
cpp#include <iostream> #include <unordered_map> #include <vector> #include <string> int main() { // Create an unordered map with string keys and vector<string> values std::unordered_map<std::string, std::vector<std::string>> myMap; // Method 1: Using the subscript operator myMap["fruits"].push_back("apple"); myMap["fruits"].push_back("banana"); // Method 2: Using the insert method myMap.insert({"vegetables", {"carrot", "broccoli"}}); // Print the contents of the unordered map for (const auto& pair : myMap) { std::cout << pair.first << ":\n"; for (const auto& item : pair.second) { std::cout << " " << item << "\n"; } } return 0; }Explanation:
-
Include Required Headers: You need to include
<iostream>,<unordered_map>,<vector>, and<string>for this example. -
Create the Unordered Map: We declare
std::unordered_map<std::string, std::vector<std::string>> myMap;. -
Inserting Values:
- Using the Subscript Operator (
[]): This can be used to initialize a vector if the key does not exist yet. We can then callpush_backon the vector associated with that key. - Using
insertMethod: This can be used to insert a key-value pair directly. Note that the value here is an initializer list for a vector.
- Using the Subscript Operator (
-
: You can iterate over the map and print each key along with its associated vector.
-