问题
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