masoud
masoud

Reputation: 56479

multimap with unique key

Using a multimap like below:

multimap<int, string> mm;
mm.insert(make_pair(1, "jack"));
mm.insert(make_pair(1, "jack"));
mm.insert(make_pair(1, "jack"));
mm.insert(make_pair(1, "joe"));
mm.insert(make_pair(2, "david"));
mm.insert(make_pair(2, "daniel"));
mm.insert(make_pair(3, "alex"));

for (multimap<int, string>::iterator itr = mm.begin(); itr != mm.end(); itr++)
{
    cout << "key: " << itr->first << ", value: " << itr->second << endl;
}

results:

key: 1, value: jack
key: 1, value: jack
key: 1, value: jack
key: 1, value: joe
key: 2, value: david
key: 2, value: daniel
key: 3, value: alex

As you can see for the key 1 there is two different values joe and jack and it's ok. But there is two duplicated <1,"jack"> in the container.

How can I get rid of that duplicated items? Is there any standard container for my requirement? Or, How we can combine existing containers to achieve my goal(The efficiency is very very important)?

Upvotes: 0

Views: 500

Answers (1)

Michael Slade
Michael Slade

Reputation: 13877

In STL you can use std::pair to create a container whose keys (or values) are composites of more than one value, so you could turn your multimap into a set:

set<pair<int, string> >

The resulting container can only contain one entry for each combination of the two values.

Upvotes: 3

Related Questions