1

I need to insert some entries into a container, but, in case the entry has two specific attributes in common with one of the previously inserted entries : it will be considered as a dupe.

The tricky part is that in case I find any dupe, I don't want any entry sharing these attributes values to be part of the container at all (not even the first one, which wasn't a dupe as it was first discovered).

I was thinking about using a multimap, with the two attributes in a pair as a key (assuming the two attributes have a well defined operator==) and a pointer to the entry as a value to index all the entries.

Once I have scanned all the entries and fulfilled my multimap, I would have iterated all over the multimap and with the help of equal_range and std::distance added, in the output container, only the entries for which I have a single occurrence.

Is that the best way of doing it in terms of efficiency, assuming I only want to use standard stl containers and tools, or eventually boost libraries ?

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
4

1 回答 1

1

我会使用地图(不是多地图),如下所示:

地图我的地图;
对于(所有条目)
{
  pair::iterator,bool> res = mymap.insert(entry);
  如果 (!res->second)
  {
    // 未插入值,此处必须已存在重复值。
    // 通过将入口指针归零来标记重复
    iter->first->second = NULL;
  }
}
// 现在使用零指针从 mymap 中删除所有项目,并且您有一个带有唯一条目的地图。
于 2012-11-22T17:33:15.287 回答