>?,c++,containers,multimap"/>

首页 > 解决方案 > 如何从多图中删除重复的元素>?

问题描述

我有一个重复的多图。当我完成元素的收集时,我想删除这些重复。

这是容器:

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;
        }
    }

标签: c++containersmultimap

解决方案


是很好的解决方案吗?

除非您在 multimap 中保持内部对排序,否则这不是一个好的解决方案,因为它会丢失重复项。如果您可以更改数据类型,那么您可以使用:

std::map<int, std::vector<std::pair<int, bool>>>

而不是std::multimap然后为每个元素排序向量并使用标准算法删除重复项,如此处所述删除字符串向量中的重复项

如果你不能,我建议使用额外的std::setstd::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;
}

推荐阅读