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

map string to vector or map different keys to one value

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

首先是将每个字符串映射到一个向量,这样当我查看密钥时,我得到 return 中的向量。 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 中数组的长度。

这两个解决方案有什么主要区别吗?哪一个会减少 faster/use 纸上内存?

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

示例 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

您有一个字符串和一系列字符串(或者可能是一组字符串,如果插入顺序不重要的话)之间的映射。让我们调用前一个键和后一个值,尽管你的第二个例子以相反的方式使用它们。

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

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

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