3 // Copyright (c) 2006-2007 Matias Capeletto
5 // Distributed under the Boost Software License, Version 1.0.
6 // (See accompanying file LICENSE_1_0.txt or copy at
7 // http://www.boost.org/LICENSE_1_0.txt)
10 /*****************************************************************************
12 *****************************************************************************/
14 #include <boost/config.hpp>
16 //[ code_mi_to_b_path_mi_hashed_indices
21 #include <boost/tokenizer.hpp>
23 #include <boost/multi_index_container.hpp>
24 #include <boost/multi_index/key_extractors.hpp>
25 #include <boost/multi_index/ordered_index.hpp>
26 #include <boost/multi_index/hashed_index.hpp>
27 #include <boost/lambda/lambda.hpp>
29 using namespace boost::multi_index;
30 namespace bl = boost::lambda;
32 // word_counter keeps the ocurrences of words inserted. A hashed
33 // index allows for fast checking of preexisting entries.
35 struct word_counter_entry
38 unsigned int occurrences;
40 word_counter_entry( std::string word_ ) : word(word_), occurrences(0) {}
43 typedef multi_index_container
50 BOOST_MULTI_INDEX_MEMBER(
51 word_counter_entry,unsigned int,occurrences),
52 std::greater<unsigned int>
56 BOOST_MULTI_INDEX_MEMBER(word_counter_entry,std::string,word)
62 typedef boost::tokenizer<boost::char_separator<char> > text_tokenizer;
67 "En un lugar de la Mancha, de cuyo nombre no quiero acordarme... "
69 "...no se salga un punto de la verdad.";
71 // feed the text into the container
74 text_tokenizer tok(text,boost::char_separator<char>(" \t\n.,;:!?'\"-"));
75 unsigned int total_occurrences = 0;
77 for( text_tokenizer::iterator it = tok.begin(), it_end = tok.end();
81 word_counter::iterator wit = wc.insert(*it).first;
82 wc.modify_key( wit, ++ bl::_1 );
85 // list words by frequency of appearance
87 std::cout << std::fixed << std::setprecision(2);
89 for( word_counter::iterator wit = wc.begin(), wit_end=wc.end();
90 wit != wit_end; ++wit )
92 std::cout << std::setw(11) << wit->word << ": "
94 << 100.0 * wit->occurrences / total_occurrences << "%"