how to eliminate duplicates in a multimap?

T

Tony Young

Hi,

I have a multimap container. I want to eliminate all "duplicate"
elements. By duplicate I mean something like (3, 4), (4, 3) and (4, 3),
in which I want to eliminate any two of these three. The most
straightforward way I can think of is to first swap every member such
that every member has its key smaller than its value. Then loop thru
the multipmap and erase duplicates (please see the loop below). Is
there a more automatic way to achieve this? Thanks for any input.

// swap first
.....

//
for (it=m.begin(); it!=m.end();)
{
IT itUB = m.upper_bound(it->first);
copy(it, itUB, inserter(mAux, mAux.begin()));
it = itUB;
}

m.swap(mAux);

Tony
 
R

Reddsci2001

How are the duplicates getting into the map? If they are being placed in
when you search for a key use find() instead of the subscript[] operator.
If this is not possible use a set instead.
 
M

Mark P

Tony said:
Hi,

I have a multimap container. I want to eliminate all "duplicate"
elements. By duplicate I mean something like (3, 4), (4, 3) and (4, 3),
in which I want to eliminate any two of these three. The most
straightforward way I can think of is to first swap every member such
that every member has its key smaller than its value. Then loop thru
the multipmap and erase duplicates (please see the loop below). Is
there a more automatic way to achieve this? Thanks for any input.

// swap first
....

//
for (it=m.begin(); it!=m.end();)
{
IT itUB = m.upper_bound(it->first);
copy(it, itUB, inserter(mAux, mAux.begin()));
it = itUB;
}

m.swap(mAux);

Tony

There may be a more clever way to do this, but you could copy all the
elements to a map whose comparison function regards (x,y) = (y,x).
Remember that the comparison fcn is lessThan so you'll need to define
each not less than the other.
 
M

Maciej Pilichowski

The most
straightforward way I can think of is to first swap every member such
that every member has its key smaller than its value.

It is not allowed -- after inserting pair into map or multimap you
cannot changed its key.

I have no idea how to deal with inverse pairs but assuming that you
want to deal only with straight pairs you don't even have to use any
find method. Just iterate through the multimap -- when previous pair
is equal to current pair erase one of them and continue iterating.
When it is unequal and you erased pair before erase previous one.

Note: after erasing the iterator is not valid.

have a nice day
bye
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top