如果值等于键,则合并映射中的条目
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)
.
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 使用std::函数映射对象方法
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- C++映射分割错误(核心转储)
- 内联映射初始化的动态atexit析构函数崩溃
- 标准::映射::合并的计算时间复杂度
- 如果值等于键,则合并映射中的条目
- 合并两个映射 c++
- 如何合并两个 mpl 映射生成新映射
- 如何使用合并合并两个地图/多映射(C 11 STL)
- 合并两个映射,对C++中相同键的值求和
- 合并两个映射<字符串,整数>
- 如何合并2个std::映射,并在第三个映射中输出结果
- 在抛出"std::bad_alloc"实例后调用的合并映射终止
- 将已排序的集合与映射合并
- c++ 11 STL在两个映射之间使用move赋值合并