Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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?)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading