2011-03-09 57 views
1

你好,我有一個std ::設置包含下列元素對:刪除對重複設置:: C++

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 

我需要找到一種方法來刪除重複項,只留與第二對最高的那些。 (對不起,如果這或標題混淆) 編輯:如果可能,不使用std :: map!

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

回答

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

無圖:

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); 
    } 
    } 
} 
+0

對不起,我編輯我的帖子,我不能使用地圖:( – Kobe 2011-03-09 23:47:57

+0

添加了一個替代沒有地圖 – Erik 2011-03-09 23:52:09

+0

哇...我沒有文字,它的工作。非常感謝你 – Kobe 2011-03-09 23:56:47

1

一個std::set似乎對自己的原始數據一個相當奇怪的容器。

無論如何,只需遍歷該集合,然後使用std::map來存儲具有最高值的對。對於每一對,如果地圖中的對具有較低的值,則更新它。

一個普通的for循環會做得很好,不要考慮for_each等等(保持簡單)。

乾杯&心連心,

+0

除非它是BOOST_FOREACH – 2011-03-09 23:40:18

+0

啊對不起,我忘了說,我不想使用的地圖(不要問爲什麼):) – Kobe 2011-03-09 23:40:33

+1

@vBx:爲什麼我們不能問爲什麼?瞭解您的限制對於幫助解決您的問題非常重要! – Cascabel 2011-03-09 23:43:29

1

注意,集的內容進行排序,首先由串,然後由整數。因此,要刪除除了每個字符串值的最高值條目之外的所有值,請查找具有該字符串值的範圍,並刪除除最後一個之外的所有值。像這樣(未經):

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

謝謝你的代碼 – Kobe 2011-03-10 00:12:39