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 81 82 83 84 85 86 87
|
#include <iostream>
#include <string>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
#include <algorithm>
#include <iterator>
using namespace boost ;
using namespace boost::multi_index ;
struct country
{
int country_code ;
std::string name ;
std::string language ;
int population ;
std::string currency ;
friend inline std::ostream& operator<< ( std::ostream& stm, const country& c )
{
return stm << "{ " << c.country_code << ", " << c.name << ", " << c.language
<< ", " << c.population << ", " << c.currency << " }" ;
}
};
template < typename TAG, typename T, T country::*MEM >
using unique_member = ordered_unique< tag<TAG>, member< country, T, MEM > > ;
template < typename TAG, typename T, T country::*MEM >
using non_unique_member = ordered_non_unique< tag<TAG>, member< country, T, MEM > > ;
int main()
{
struct by_code{};
struct by_name{};
struct by_lang{};
struct by_pop{};
struct by_currency{};
using country_db = multi_index_container
<
country,
indexed_by
<
sequenced<>,
unique_member< by_code, int, &country::country_code >,
unique_member< by_name, std::string, &country::name >,
non_unique_member< by_lang, std::string, &country::language >,
non_unique_member< by_pop, int, &country::population >,
non_unique_member< by_currency, std::string, &country::currency >
>
>;
country_db db ;
db.push_back( { 56, "Spain", "Spanish", 123, "Drachma" } ) ;
db.push_back( { 68, "Lithuania", "Lithuanian", 4567, "Lira" } ) ;
db.push_back( { 92, "Armenia", "Armenian", 890, "Zlotty" } ) ;
db.push_back( { 11, "Mexico", "Spanish", 2345, "Taka" } ) ;
db.push_back( { 38, "Brazil", "Spanish", 345, "Rouble" } ) ;
db.push_back( { 93, "Austria", "German", 6789, "Yen" } ) ;
auto to_stdout = std::ostream_iterator<country>( std::cout, "\n" ) ;
// list by country code
std::copy( db.get<by_code>().begin(), db.get<by_code>().end(), to_stdout ) ;
// list Spanish speaking countries
{
std::cout << "\nlanguage is 'Spanish'\n-----------\n" ;
const auto& iter = db.get<by_lang>().equal_range("Spanish") ;
std::copy( iter.first, iter.second, to_stdout ) ;
}
// print out the population of 'Armenia'
std::cout << "\npopulation of 'Armenia': "
<< db.get<by_name>().find("Armenia")->population << '\n' ;
// list countries with population > 999 and less than 5000
{
std::cout << "\npopulation > 900 && population < 5000\n------------------\n" ;
const auto& begin = db.get<by_pop>().upper_bound(999) ;
const auto& end = db.get<by_pop>().lower_bound(5000) ;
std::copy( begin, end, to_stdout ) ;
}
}
|