jeudi 4 novembre 2021

How to append more items to an existing vector contained in the value field of a std::map?

I have a std::vector<std::string>>. Following is my full program:

#include <iostream>
#include <vector>
#include <string>
#include <map>
 
int main() {
    std::cout << " -- Beginining of program -- " << std::endl;
    
    std::map<std::string, std::vector<std::string>> my_map_2;
    std::vector<std::string> s = {"a", "b", "c"};
    my_map_2.insert(std::make_pair("key1", s));
    std::vector<std::string> s2 = {"d", "e", "f"};
    my_map_2.insert(std::make_pair("key1", s2));

    for(auto const &map_item: my_map_2) {
        std::cout << map_item.first << " " << map_item.second[0] << std::endl;
        std::cout << map_item.first << " " << map_item.second[1] << std::endl;
        std::cout << map_item.first << " " << map_item.second[2] << std::endl;
        std::cout << map_item.first << " " << map_item.second[3] << std::endl;
        std::cout << map_item.first << " " << map_item.second[4] << std::endl;
        std::cout << map_item.first << " " << map_item.second[5] << std::endl;
    }
    
    std::cout << " -- End of program -- " << std::endl;
    return 0;
}

Problem:
I don't see the items of s2 when I print values of my_map_2. I see them only if I add s2 with a new key! If I do my_map_2.insert(std::make_pair("key2", s2)) instead of my_map_2.insert(std::make_pair("key1", s2)), I do see the items.

Question:
So, my question is, how to I append more items to the vector pointed to by key1 of my_map_2?

Aucun commentaire:

Enregistrer un commentaire