gpt4 book ai didi

C++ 在键上将两个映射相交,保留第一个映射的值

转载 作者:行者123 更新时间:2023-11-27 23:04:04 27 4
gpt4 key购买 nike

我在使用 C++ 以及 map 和交集时遇到了问题。

有 3 张 map ,前两张是 map<int, double> , 最后一个是 map<int, CustomType> .我想从前 2 个 map 中删除所有 map 键实例,这些实例在第 3 个 map 中不作为键存在。简而言之,我有第三张 map 包含对象列表,前两张 map 包含有关对象的一些数据。在某个时间点,包含对象的 map 被清理并删除了一些项目(用户交互),现在想要分别清理其他两个 map 。

我试过以下方法:

map<int, double> map1, map2;
map<int, CustomType> map3;
for (auto it = map1.cbegin(); it != map1.cend(); )
{
if ( map3.find(it->first) == map3.end() )
{
map2.erase(it);
map1.erase(it++);
}
else ++it;
}

这在 map1.erase 行上给我一个错误“未分配正在释放的指针”。我研究过 set_intersection,但我认为它在这种情况下不起作用,因为值会不同。

感谢任何帮助。

最佳答案

你需要迭代map1map2独立地。您不能使用 map1 的迭代器操作另一个映射(从 erasemap2 或使用 map2 执行任何其他操作)。
所以代码应该是这样的:

map<int, double> map1, map2;
map<int, CustomType> map3;
for (auto it = map1.cbegin(); it != map1.cend(); )
{
if ( map3.find(it->first) == map3.end() )
it = map1.erase(it);
else
++it;
}

for (auto it = map2.cbegin(); it != map2.cend(); )
{
if ( map3.find(it->first) == map3.end() )
it = map2.erase(it);
else
++it;
}

关于C++ 在键上将两个映射相交,保留第一个映射的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24819996/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com