2011-10-17 98 views
3

有沒有什麼好的方法可以實現下面所需的輸出而不必刪除相同的值或創建另一個列表/矢量等?我正試圖將在不同文檔中找到的單詞映射到他們的文檔名稱,如所需輸出中所示。迭代時跳過相同的multimap值

#include <iostream> 
#include <fstream> 
#include <string> 
#include <map> 
#include <sstream> 

using namespace std; 

multimap<string,string> inverts; 
multimap<string,string>::iterator mit; 
multimap<string,string>::iterator rit; 
pair<multimap<string,string>::iterator,multimap<string,string>::iterator> ret; 

int main(int argc, char* argv[]) 
{ 
ifstream infile; 

for(int i=1;i<argc;i++) 
{ 
    char* fname=argv[i]; 
    char line[1024]; 
    string buff; 
    infile.open(fname); 

    while(infile.getline(line,1024)) 
    { 
     stringstream ss(line); 
     while(ss >> buff) 
      inverts.insert(pair<string,string>(buff,fname)); 
    } 

    infile.close(); 

} 

for(mit=inverts.begin();mit!=inverts.end();mit++) 
{ 
    string first=(*mit).first; 
    cout<<first; 
    ret=inverts.equal_range(first); 

    for(rit=ret.first;rit!=ret.second;rit++) 
     cout<<" "<<(*rit).second; 
    cout<<endl; 

} 


return 0; 

}

Output is: 

> ./a.out A B 
cat A 
dog A B 
dog A B 
fox A B 
fox A B 
lion B 

I need this output: 

> ./a.out A B 
cat A 
dog A B 
fox A B 
lion B 
+0

http://stackoverflow.com/questions/9371236/is-there-an-iterator-across-unique-keys-in-a- stdmultimap –

+0

http://stackoverflow.com/questions/247818/stlmultimap-how-do-i-get-groups-of-data –

回答

5

你可以改變invertsmap<string,set<string>>,每個單詞映射到一套地方出現文件名。

0

典型的多地圖迭代保持兩個迭代:

for (it1 = inverts.begin(), it2 = it1, end = inverts.end(); it1 != end; it1 = it2) 
{ 
    // iterate over distinct values 

    // Do your once-per-unique-value thing here 

    for (; it2 != end && *it2 == *it1; ++it2) 
    { 
    // iterate over the subrange of equal valies 
    } 
}