将字符串映射到矢量或将不同的键映射到一个值

map string to vector or map different keys to one value

本文关键字:映射 一个 字符串      更新时间:2023-10-16

我需要将单个字符串映射到多个字符串,为此,我想到了两种不同的解决方案:

第一种是将每个字符串映射到一个向量,以便当我查看键时,我得到向量作为回报。
std::unordered_map<std::string, std::vector<std::string>>使用此解决方案意味着我只需要查找一次键,但随后我必须迭代数组以找到所需的正确字符串。

我认为的第二个解决方案是使用向量中包含的每个字符串(我知道它们是唯一的)作为键,并将它们映射到解决方案 1 中的键。
std::unordered_map<std::string, std::string>使用此解决方案意味着我需要查找一个键 n 次(其中 n 是解决方案 1 中数组的长度),在我的映射中,我对许多键具有相同的值(我不知道这是否重要最终),但我直接拥有我需要的字符串。

示例 1:

std::unordered_map<std::string, std::vector<std::string>> map;
std::vector<std::string> arr = {"hello", "world"};
map["greetings"] = array;

示例 2:

std::unordered_map<std::string, std::string> map;
map["hello"] = "greetings";
map["world"] = "greetings";

出于我的程序的目的,我最终拥有的字符串(来自解决方案 1 数组的值或来自解决方案 2 的值)并不重要,只要我有办法将它们相互映射,以便两个解决方案都是可行的。 我没有办法提前知道解决方案 1 中数组的长度。

这两种解决方案有什么重大区别吗?哪一个会更快/在纸上使用更少的内存?

一个字符串与一系列字符串(如果广告顺序不重要,则可能是一组字符串)之间存在映射。让我们调用前一个键和后一个值,尽管您的第二个示例以相反的方式使用它们。

示例 1 允许您有效地查找与特定键关联的所有值。因此,方法一更快,方法二较慢。

示例 2 允许您有效地查找特定值映射到的键。因此,方法二更快,方法一更慢。

如您所见,这两个示例都比另一个更快。

你的两个选项做不同的事情。

示例 1:

std::unordered_map<std::string, std::vector<std::string>> map;
map["greetings"] = {"hello", "world"};
map["farewells"] = {"goodbye", "cruel", "world"};
for(auto && pair : map) {
for(auto && value : pair.second) {
std::cout << pair.first << value;
}
}
// greetings hello
// greetings world
// farewells goodbye
// farewells cruel
// farewells world

示例 2:

std::unordered_map<std::string, std::string> map;
map["hello"] = "greetings";
map["world"] = "greetings";
map["goodbye"] = "farewells";
map["cruel"] = "farewells";
map["world"] = "farewells";
for(auto && pair : map) {
std::cout << pair.second << pair.first;
}
// greetings hello
// farewells goodbye
// farewells cruel
// farewells world