c++ - 删除重复条目

标签 c++ stl indexing complexity-theory multimap

我需要将一些条目插入到容器中,但是,如果该条目与先前插入的条目之一有两个共同的特定属性:它将被视为欺骗。

棘手的部分是,如果我发现任何欺骗,我根本不希望任何共享这些属性值的条目成为容器的一部分(甚至不是第一个,它不是欺骗,因为它是首次发现)。

我正在考虑使用多重映射,将成对的两个属性作为键(假设这两个属性具有明确定义的运算符==)和指向条目的指针作为索引所有条目的值。

一旦我扫描了所有条目并完成了我的多重映射,我将遍历整个多重映射并在 equal_range 和 std::distance 添加的帮助下,在输出容器中,只有我有一个单一的条目发生。

假设我只想使用标准的 STL 容器和工具,或者最终提升库,这是否是效率方面的最佳方式?

typedef std::pair<attribute1,attribute2> key;
multimap<key, entry*> multimap;
typedef multimap<key, entry*>::iterator MultimapIter; 

// process all the entries and fullfill the multimap

MultimapIter iter;
for(iter = multimap.begin(); iter != multimap.end(); ++iter)
{
    std::pair<MultimapIter,MultimapIter> keyRange = 
            multimap.equal_range(iter->first);

    if(std::distance(keyRange.first, keyRange.second) != 1)
        iter = --keyRange.second;
    else
        // Fill the output container with the entry
}

// Destroy the multimap

最佳答案

我会像这样使用 map (不是多 map ):

map mymap;
for (all entries)
{
  pair::iterator,bool> res = mymap.insert(entry);
  if (!res->second)
  {
    // Value not inserted, a duplicate must already be here.
    // Mark duplicate by zeroing the entry pointer
    iter->first->second = NULL;
  }
}
// Now remove all items from mymap with a zero pointer and you have a map with unique entries left over.

关于c++ - 删除重复条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13517523/

相关文章:

c++ - STL中map和hashmap有什么区别

pandas - 从过滤后的 Pandas 数据框中获取整数索引值

indexing - 如何在 mongoengine 中创建一个索引为 unique=True 和 sparse=True

c++ - 单元测试函数对象是否被调用

c++ - 获取CString的结束位置

c++ - 如何从 QLineEdit 小部件获取文本并在状态机中使用它?

C++ STL : Container Recreation or Reuse after clearing?

c++ - push_back std::pair 进入 std::vector 错误

c++ - Linux 中的交换内存速度

swift - 在结构中搜索,传递数组的索引?