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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include <iostream>
#include <list>
#include <functional>
#include <map>
struct frame
{
frame( int aa, int bb, const std::string& t ) : a(aa), b(bb), tag(t) {}
int a ;
int b ;
using key_type = std::pair<int,int> ;
key_type key() const { return key_type(a,b) ; }
std::string tag ;
char other_data[1000] {0} ;
};
std::ostream& operator<< ( std::ostream& stm, const frame& a )
{ return stm << "{(" << a.a << ',' << a.b << "):" << a.tag << "}" ; }
struct containers
{
std::list<frame> lst ;
std::map< frame::key_type, std::reference_wrapper<frame> > map ;
bool insert( const frame& a )
{
if( map.find( a.key() ) == map.end() )
{
lst.push_back(a) ;
map.emplace( a.key(), lst.back() ) ;
return true ;
}
return false ;
}
bool erase( frame::key_type key ) ; // if present, erase from both lst and map
frame& look_up( frame::key_type key )
{
auto iter = map.find(key) ;
if( iter == map.end() ) throw "not found" ;
return iter->second ;
}
};
int main()
{
containers c ;
c.insert( { 9, 6, "one" } ) ;
c.insert( { 4, 0, "two" } ) ;
c.insert( { 1, 8, "three" } ) ;
c.insert( { 2, 3, "four" } ) ;
c.insert( { 1, 5, "five" } ) ;
c.insert( { 2, 2, "six" } ) ;
// iterate in list order
for( const frame& a : c.lst ) std::cout << a << ' ' ;
std::cout << '\n' ;
// iterate in key order
for( const auto& p : c.map ) std::cout << p.second << ' ' ;
std::cout << '\n' ;
// look up (2,3), (6,7)
try
{
std::cout << "looking up (2,3): " ;
frame& a1 = c.look_up( frame::key_type(2,3) ) ;
std::cout << "found it - tag == " << a1.tag << '\n' ;
std::cout << "looking up (6,7): " ;
frame& a2 = c.look_up( frame::key_type(6,7) ) ;
std::cout << "found it - tag == " << a2.tag << '\n' ;
}
catch(...)
{
std::cout << "lookup failed\n" ;
}
}
|