user1871217
user1871217

Reputation: 35

Remove duplicate key in a multimap

I have a multimap:

std::multimap < string, string >::iterator iter_map;
multimap < string, set<string> > my.map;  

Typical output and data structure:

key        -    value

bird       -    air
bird       -    earth
fish       -    water
lion       -    earth
lion       -    water 

I would like change the data structure (no only print to) such that that the new data would be:

bird      -    air, earth
fish      -    water
lion      -    earth, water

In other way, how to eliminate the duplicate keys?

I did this:

int size_mmap = namesMultiMap1.size();
pair<multimap<string,string>::iterator,multimap<string,string>::iterator> ret;

for (int i = 0; i < 1; i++){

   cout << " xxx "<< " =>";
   ret = namesMultiMap1.equal_range("xxx");

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

}

In this way I print the values associeted at a key xxx but I print a element at once. I would like to print all keys and values. I need automated this because the map is big. If I iterate using a iterator for namesMultiMap1 a print the repeat keys.

Upvotes: 0

Views: 1833

Answers (1)

piokuc
piokuc

Reputation: 26184

Ok, this can be done like follows. Notice, that the type of the result is map<string, set<string> >, not multimap < string, set<string> > as you wanted, cause you don't want duplicated keys in it, so map makes more sense.

#include <map>
#include <set>
#include <string>
#include <iostream>
#include <iterator>

using namespace std;

typedef multimap<string,string> mm; 
typedef map<string, set<string> > ms; 

ms convert(const mm& m)
{   
    ms r;

    for (mm::const_iterator it = m.begin(); it != m.end(); ++it)
    {   
        set<string>& s(r[it->first]);
        s.insert(it->second);
    }   

    return r;
}   


int main()
{   
    mm m;
    m.insert(make_pair("john", "kowalski"));
    m.insert(make_pair("john", "smiths"));
    m.insert(make_pair("mary", "doe"));
    m.insert(make_pair("mary", "walker"));

    ms s(convert(m));

    for (ms::iterator it = s.begin(); it != s.end(); ++it)
    {   
        cout << it->first << ": ";
        set<string> &st(it->second);
        copy(st.begin(), st.end(), ostream_iterator<string>(cout, ", "));
        cout << endl;
    }   
    return 0;
}   

This will print:

john: kowalski, smiths,
mary: doe, walker,

Upvotes: 2

Related Questions