开发者

Remove pair duplicates from a std::set C++

Hello I have a std::set of pair that contains the following elements:

set<pair<string, int> > mapElem;

apples 1
apples 2
at 1
eating 1
eating 2
football 1
going 1
today 1
today 2
today 3
today 4
today 5
tommy 1
tommy 2

I need to find a way to remove the duplicates and to remain only 开发者_开发百科the ones with the highest second pair. (Sorry if this or the title is confusing) edit: if possible without using std::map !

apples 2
at 1
eating 2
football 1
going 1
today 5
tommy 2


map<string, int> aMap(mapElem.begin(), mapElem.end());
set<pair<string, int> > Temp(aMap.begin(), aMap.end());
mapElem.swap(Temp);

Without map:

set<pair<string, int> >::iterator nextit = mapElem.begin();
while (nextit != mapElem.end()) {
  set<pair<string, int> >::iterator it = nextit++;
  if (nextit != mapElem.end()) {
    if (it->first == nextit->first) {
      mapElem.erase(it);
    }
  }
}


Note that the contents of the set are sorted, first by the string, then by the integer. So to remove all but the highest-valued entry for each string value, find the range with that string value and remove all but the last one. Something like this (untested):

for (iterator i = map.begin(); i != map.end(); ) {
    for (iterator j = i; j != map.end(); ) {
        iterator k = j++;
        if (j == map.end() || j->first != i->first) {
            map.erase(i,k);
            i = j;
        }
    }
}


A std::set seems a rather odd container for your original data.

Anyway, just iterate over the set, and use a std::map to store the pairs with highest value. For each pair, if the pair in the map has lower value, update it.

An ordinary for-loop will do nicely, don't think about for_each and such (keep it simple).

Cheers & hth.,

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜