Another example with maps.
Run the program like this:
programname <fileCount> <fileIgnore>.
This will count the words in fileCount, that do not appear in fileIgnore.
Code:
#include <cstdlib>
#include <iostream>
#include <map>
#include <string>
#include <fstream>
using namespace std;
bool readWords( const string& fileName, map<string,int>& words ) {
ifstream in( fileName.c_str() );
if ( in ) {
string word ;
while( in >> word ) {
words[word]++;
}
return true ;
}
return false ;
}
size_t countWords( map<string,int>& words, map<string,int>& ignore ) {
size_t n = 0 ;
for ( map<string,int>::iterator i=words.begin(); i!=words.end(); ++i ) {
string word = i->first ;
if ( ignore.find( word ) == ignore.end() ) {
n += i->second ;
}
}
return n ;
}
int main( int argc, char* argv[] ) {
if ( argc == 3 ) {
string fileCount = argv[1] ;
string fileIgnore = argv[2] ;
map<string,int> words, ignore ;
if ( readWords(fileCount,words) && readWords(fileIgnore,ignore) ) {
cout << countWords(words,ignore) << endl ;
}
else {
cout << "Error reading files" << endl ;
}
}
else {
cout << "pass 2 arguments: <fileCount> <fileIgnore>" << endl ;
}
return 0 ;
}