【发布时间】:2021-02-09 06:28:58
【问题描述】:
我尝试在地图值中找到也出现在其他值中的元素。
{
1: ["a", "b", "c", "d"],
2: ["a", "c"],
3: ["c", "d"],
4: ["a", "c"]
}
=>
{
"a": [ 1, 2, 4 ], // a occurs in the map which key are 1/2/4
"b": [ 1 ],
"c": [ 1, 2, 3, 4],
"d": [ 1, 3 ]
}
我的实现是:
map<int, set<string>> map1 = {
{ 1, set<string>{"a", "b", "c", "d"} },
{ 2, set<string>{"a", "c"} },
{ 3, set<string>{"c", "d"} },
{ 4, set<string>{"a", "c"} },
};
map<string, set<int>> map2;
for (const auto& [id, str_set] : map1) {
for (const auto& s : str_set) {
if (map2.count(s) == 0) {
map2[s] = std::set<int>{id};
} else {
map2[s].emplace(id);
}
}
}
看起来效率不高。那么有没有其他方法可以加快速度呢? 或者是否有任何适当的数据结构/算法来处理我想要的这些数据?
【问题讨论】:
-
Looks like it's not efficient为什么? -
@ShridharRKulkarni 我只是不喜欢嵌套
-
除此之外:你不需要
if,map2[s].emplace(id);在这两种情况下都是正确的
标签: c++ algorithm data-structures