我在使用 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,但我认为它在这种情况下不起作用,因为值会不同。
感谢任何帮助。
最佳答案
你需要迭代map1
和 map2
独立地。您不能使用 map1
的迭代器操作另一个映射(从 erase
到 map2
或使用 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/