1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#include <iostream>
#include <string>
#include <map>
int main()
{
std::multimap<int,std::string> mmap { {0,"ab"}, {0,"cd"}, {0,"ab"}, {0,"ef"}, {1,"gh"}, {1,"ij"} } ;
using kv_pair = std::pair<const int,std::string> ;
std::map< const kv_pair*, const kv_pair* > links ;
// link {0,"cd"} to {1,"ij"}
// get address of node {0,"cd"}
kv_pair* key = nullptr ;
for( auto [iter,till] = mmap.equal_range(0) ; iter != till ; ++iter )
if( iter->second == "cd" ) key = std::addressof(*iter) ;
// get address of node {1,"ij"}
kv_pair* value = nullptr ;
for( auto [iter,till] = mmap.equal_range(1) ; iter != till ; ++iter )
if( iter->second == "ij" ) value = std::addressof(*iter) ;
// create the link
if( key && value ) links.emplace( key, value ) ;
// test it
for( const kv_pair& pair : mmap )
{
const auto iter = links.find( std::addressof(pair) ) ;
if( iter != links.end() )
{
std::cout << '{' << iter->first->first << ',' << iter->first->second << "} is linked to {"
<< iter->second->first << ',' << iter->second->second << "}\n" ;
}
}
}
|