/* engspanUI.cpp * Anthony Larrain */ #include #include #include #include #include using namespace std; class Pair; typedef vector list_type; class Pair { private: string key; string value; public: Pair(string k, string v) : key(k), value(v) {} const string & getKey() const; const string & getValue() const; string toString() const; }; class Dictionary { private: list_type list; int binSearch(string k, int l, int h); string notFound; public: Dictionary(list_type& l) : list(l), notFound("word not found") {} const string & lookup(const string & k); }; bool loadData(list_type & list, string filename); int main(int argc, char *argv[]) { list_type list; string response,word,file("engspan.txt"); if(!loadData(list,file)){ cout << "Problem loading words " << endl; system("PAUSE"); return 1; } Dictionary dict(list); for(;;){ cout << "Enter English Word (cntl-z to quit)" << endl; cin >> word; if(!cin){ break; } cout << word << " in spanish is .. " << dict.lookup(word) << endl; } system("PAUSE"); return EXIT_SUCCESS; } /* P A I R M E M B E R F U N C T I O N S */ const string & Pair::getKey() const{ return key; } const string & Pair::getValue() const{ return value; } string Pair::toString() const{ string pairString("("); pairString += key + " , " + value + ")"; return pairString; } /* D I C T I O N A R Y M E M B E R F U N C T I O N S */ const string & Dictionary::lookup(const string & k){ int i = binSearch(k, 0, list.size() - 1); if( i == -1 ) { return notFound; }else{ return list[i].getValue(); } } int Dictionary::binSearch(string k, int low, int high){ // not found if( low > high ){ return -1; } else{ // get the midpoint int mid = (low + high) / 2; // Check to see if the key is equal to the object at the end // of the left sub half, // if so we found the index of the key // operator == is overloaded in the c++ string class. if(k == list[mid].getKey()){ return mid; } // If the key is less than the object at the end of the left sub half // do binary search on the left sub half // operator < is overloaded in the c++ string class else if(k < list[mid].getKey()) { return binSearch(k,low,mid - 1); } // else the key is greater than, so do binary search // on the right sub half. else{ return binSearch(k, mid+1, high); } } } /* G L O B A L F U N C T I O N */ bool loadData(list_type & list, string filename){ ifstream is (filename.c_str()); if(!is){ return false; }else{ string key,value,line; while(is){ getline(is,line); int pos = line.find(";"); key = line.substr(0,pos); value = line.substr(pos + 1); Pair p(key,value); list.push_back(p); } } return true; }