Skip same multimap values when iterating

荒凉一梦 提交于 2020-01-13 18:05:32

问题


Is there any good way to achieve the desired output below without having to remove the same values or creating another list/vector etc? I am trying to map words found in different documents to their document names as shown in the desired output.

#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

回答1:


You could change inverts into map<string,set<string>>, mapping each word to the set of file names where it appears.




回答2:


A typical multi-map iteration keeps two iterators:

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
   }
}


来源:https://stackoverflow.com/questions/7792682/skip-same-multimap-values-when-iterating

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!