Search code examples
c++11stdvectorstdmapstdstring

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?


Solution

  • Get iterator to key1, and just pushs back new items to existing vector:

    std::vector<std::string> s2 = {"d", "e", "f"};
    auto it = my_map_2.find("key1");
    if (it != my_map_2.end())
        std::move(s2.begin(), s2.end(), std::back_inserter(it->second));
    else 
        my_map_2.insert(std::make_pair("key1",std::move(s2)));
    

    To see: d,e,f you have to access 3,4 and 5 indices of vector. (You want to append new items, or just override existed items for given key?)