c++ - 如何从多图中删除重复的元素>?
问题描述
我有一个重复的多图。当我完成元素的收集时,我想删除这些重复。
这是容器:
std::multimap<int, std::pair<int, bool>> container;
以下代码在迭代中。(它是原始版本的更简单版本)
container.emplace(LeafId, std::make_pair(NodeId, isElectronic));
是很好的解决方案吗?
std::pair<int, std::pair<int, bool>> lastValue {-1 , {-1, -1}};
for (auto it = container.cbegin(); it != container.cend();)
{
if (it->first == lastValue.first && it->second == lastValue.second)
{
it = container.erase(it);
} else
{
lastValue = *it;
++it;
}
}
解决方案
是很好的解决方案吗?
除非您在 multimap 中保持内部对排序,否则这不是一个好的解决方案,因为它会丢失重复项。如果您可以更改数据类型,那么您可以使用:
std::map<int, std::vector<std::pair<int, bool>>>
而不是std::multimap
然后为每个元素排序向量并使用标准算法删除重复项,如此处所述删除字符串向量中的重复项
如果你不能,我建议使用额外的std::set
或std::unordered_set
:
std::set<std::pair<int, bool>> tset;
int lastValue = 0;
for (auto it = container.cbegin(); it != container.cend();)
{
if( it->first != lastValue ) {
tset.clear();
lastValue = it->first;
}
if( !tset.insert( it->second ).second )
it = container.erase( it );
else
++it;
}
推荐阅读
- javascript - 当具有空格分隔值时,JSON 字符串化字符串在 data 属性内中断
- sql - 在 SSIS 字符串参数中执行 SQL 任务
- amazon-web-services - 如何使用boto3在不同账户的安全组之间添加安全组规则?
- c# - 两个同名型号?
- gradle - Gradle 多模块
- sql - 将 AD 日期转换为日期,然后搜索特定日期
- sparql - 如何在 SPARQL 中有效地设计嵌套的 OPTIONAL 子句
- concurrency - 与 Java 8 Streams 并行映射到多个映射
- r - 从 DocumentTermMatrix 中删除停止短语
- swift - 如何从 MTKView 无缝切换到 UIView 显示