[英]Merge entries in map if value equals key
我有一个带有以下值的std :: map:
2 31
4 36
5 29
6 24
24 49
25 83
29 63
36 42
42 79
现在,如果值存在键,我想“合并”值。 所以期望的输出(数据结构无关)将是:
2 31
4 36 42 79
5 29 63
6 24 49
25 83
我已经尝试迭代遍历地图并对每个值使用std :: find。 但我遇到的矢量大小超过3的问题,对于大型地图来说似乎非常慢。 这是一个小例子,没有给出所需的输出:
int main(int argc, char** argv)
{
std::map<int, int> my_map = { {2, 31}, {4, 36}, {5, 29}, {6, 24}, {24, 49}, {25, 83}, {29, 63}, {36, 42}, {42, 79} };
std::vector<int> temp_vec;
std::vector<std::vector<int>> destination_vec;
for (auto it = my_map.begin(); it != my_map.end(); ++it) {
std::map<int, int>::iterator map_iterator = my_map.find(it->second);
if (map_iterator == my_map.end()) {
temp_vec.push_back(it->first);
temp_vec.push_back(it->second);
}
else {
temp_vec.push_back(it->first);
temp_vec.push_back(it->second);
temp_vec.push_back(map_iterator->second);
// I stopped here because I could try another if loop here or a while loop for the whole process but it seems very inefficient
}
destination_vec.push_back(temp_vec);
temp_vec.clear();
}
}
假设您的地图无法链接较小的值( {{1, 42},{2, 1}}
)。
您可以使用:
std::map<int, std::vector<int>> foo(std::map<int, int> m)
{
std::map<int, std::vector<int>> res;
while (!m.empty())
{
auto it = m.begin();
const auto key = it->first;
auto& v = res[key];
while (it != m.end()) {
auto value = it->second;
v.push_back(value);
m.erase(it);
it = m.find(value);
}
}
return res;
}
复杂度是O(n log n)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.