【问题标题】:How can i erase duplicated elements from a multimap<int, std::pair<int, bool>>?如何从 multimap<int, std::pair<int, bool>> 中删除重复的元素?
【发布时间】:2020-09-09 14:57:48
【问题描述】:

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

这是容器:

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

【问题讨论】:

  • 你可以比较std::pairoperator==你不必手动写
  • 喜欢:std::pair> lastValue {-1 , {-1, -1}}; ?
  • 你的意思是std::pair&lt;int, bool&gt;&gt; lastValue{ -1, {-1, -1};?使用std::map,它不会编译不在if,不在lastValue = *it;,请更正
  • 是的。我更正了代码。
  • std::adjacent_find 查找重复项然后将其删除吗?

标签: c++ containers multimap


【解决方案1】:

这是好的解决方案吗?

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

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

而不是std::multimap,然后为每个元素排序向量并使用此处描述的标准算法删除重复项Removing duplicates in a vector of strings

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

【讨论】:

  • 对,完全忘记了排序部分。谢谢楼主
  • 我无法将我的数据类型更改为:std::map>> 所以这就是我问这个问题的原因。我会尝试。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-14
  • 2015-08-18
  • 2011-10-29
  • 2014-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多