Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <map>
- #include <vector>
- template <typename K, typename V, typename R> class IMapReduce
- {
- public:
- virtual ~IMapReduce() {}
- virtual void map( K key, V values ) = 0;
- virtual std::map<K, R> reduce() = 0;
- };
- #pragma once
- #include "imapreduce.h"
- #include <string>
- #include <map>
- #include <vector>
- class WordCount : public IMapReduce<std::string, std::string, int>
- {
- public:
- WordCount(void);
- ~WordCount(void);
- virtual void map( std::string key, std::string values );
- virtual std::map<std::string, int> reduce();
- private:
- std::map<std::string, int> m;
- std::vector<std::pair<std::string, int>> preReduce;
- };
- #include "WordCount.h"
- WordCount::WordCount()
- {}
- WordCount::~WordCount()
- {}
- void WordCount::map( std::string key, std::string values )
- {
- unsigned int cur = 0;
- while( cur < values.length() )
- {
- int next = values.find( ' ', cur );
- if( next == - 1)
- {
- preReduce.insert( preReduce.begin(), std::pair<std::string, int>( values.substr( cur ), 1 ) );
- break;
- }
- else
- preReduce.insert( preReduce.begin(), std::pair<std::string, int>( values.substr( cur, next - cur ), 1 ) );
- cur += next - cur + 1;
- }
- }
- std::map<std::string, int> WordCount::reduce()
- {
- if( preReduce.size() <= 0 )
- {
- return m;
- }
- std::vector<std::pair<std::string, int>>::iterator it;
- it = preReduce.begin();
- for( std::vector<std::pair<std::string, int>>::iterator it = preReduce.begin(); it < preReduce.end(); it++ )
- {
- if( m.find( (*it).first ) == m.end() )
- {
- m.insert( *it );
- }
- else
- {
- (*m.find( (*it).first )).second++;
- }
- }
- return m;
- }
- #include "WordCount.h"
- #include <iostream>
- using namespace std;
- int main( char **args, int argc )
- {
- WordCount test;
- test.map( "cool", "a a b c b cool people are nice to me and they are nice to other people as well a a a a a a a" );
- map<std::string, int> m = test.reduce();
- map<std::string, int>::iterator it;
- for( it = m.begin(); it != m.end(); it++ )
- cout << (*it).first << "\t: " << (*it).second << endl;
- char t[12];
- cin >> t;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement