You can do it for example the following way
#include <iostream>
#include <map>
#include <iterator>
int main()
{
std::multimap<int, int> multi;
multi.insert( { 1, 1 } );
multi.insert( { 1, 12 } );
multi.insert( { 2, 500 } );
multi.insert( { 2, 789 });
multi.insert( { 1, 888 } );
for ( const auto &item : multi )
{
std::cout << "{ " << item.first << ", " << item.second << " } ";
}
std::cout << '\n';
if ( !multi.empty() )
{
for ( auto prev = std::begin( multi ),
next = std::begin( multi ),
last = std::end( multi );
++next != last; )
{
if ( next->first == prev->first ) prev = multi.erase( prev );
else ( ++prev );
}
}
for ( const auto &item : multi )
{
std::cout << "{ " << item.first << ", " << item.second << " } ";
}
std::cout << '\n';
return 0;
}
The program output is
{ 1, 1 } { 1, 12 } { 1, 888 } { 2, 500 } { 2, 789 }
{ 1, 888 } { 2, 789 }
If you want to create a copy with unique keys then you can use the standard algorithm std::unique_copy. For example
#include <iostream>
#include <map>
#include <iterator>
#include <algorithm>
int main()
{
std::multimap<int, int> multi;
multi.insert( { 1, 1 } );
multi.insert( { 1, 12 } );
multi.insert( { 2, 500 } );
multi.insert( { 2, 789 });
multi.insert( { 1, 888 } );
for ( const auto &item : multi )
{
std::cout << "{ " << item.first << ", " << item.second << " } ";
}
std::cout << '\n';
std::multimap<int, int> multi2;
std::unique_copy( std::rbegin( multi ), std::rend( multi ),
std::inserter( multi2, std::end( multi2 ) ),
[]( const auto &a, const auto &b )
{
return a.first == b.first ;
} );
for ( const auto &item : multi2 )
{
std::cout << "{ " << item.first << ", " << item.second << " } ";
}
std::cout << '\n';
return 0;
}
The program output is the same as shown above
{ 1, 1 } { 1, 12 } { 1, 888 } { 2, 500 } { 2, 789 }
{ 1, 888 } { 2, 789 }