如何将更多项目附加到包含在 std::map 的值字段中的现有向量?

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

我有一个std::vector<std::string>>。以下是我的完整程序:

#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;
}

问题:
当我打印 my_map_2 的值时,我没有看到 s2 的项目。我只有在使用新密钥添加 s2 时才能看到它们!如果我 my_map_2.insert(std::make_pair("key2", s2)) 而不是 my_map_2.insert(std::make_pair("key1", s2)),我确实会看到这些项目。

问题:
所以,我的问题是,如何向 my_map_2key1 指向的向量追加 更多项?

获取 key1 的迭代器,并将新项目推回现有向量:

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

要查看:d、e、f,您必须访问向量的 3、4 和 5 索引。 (您想附加新项目,还是只覆盖给定键的现有项目?)

以下失败,因为密钥已被占用:

std::vector<std::string> s2 = {"d", "e", "f"};
my_map_2.insert(std::make_pair("key1", s2));    // fails

要附加到映射向量,您可以这样做:

auto& vec = my_map_2["key1"];    // get reference to the existing vector
vec.insert(vec.end(), s2.begin(), s2.end()); // append to it

要查看向量中的键和所有值,您可以将循环更改为:

for(auto const&[key, value]: my_map_2) {
    for(const std::string& str : value) {
        std::cout << key << ' ' << str << '\n';
    }
}

my_map_2["key1"] 始终是有效向量。可以直接insert进去

#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["key1"].insert(my_map_2["key1"].end(), s.begin(), s.end());
    std::vector<std::string> s2 = {"d", "e", "f"};
    my_map_2["key1"].insert(my_map_2["key1"].end(), s2.begin(), s2.end());

    for(auto const &map_item: my_map_2) {
        for(auto const &value: map_item.second) {
            std::cout << map_item.first << " " << value << std::endl;
        }
    }
    
    std::cout << " -- End of program -- " << std::endl;
    return 0;
}