Other features
– transform() with a home-made functor
– many for_each calls
– erase-remove idiom
——————
#include
#include
#include
#include
#include
#include
using namespace std;
using namespace __gnu_cxx;
hash_set uniqueChars(256); // only 256 characters exist in ascii
list abbreviations;
class suffixAdder {
const char suffix;
public:
suffixAdder(const char c) :
suffix(c) {
}
// This operator() actually requires an argument!
const string & operator()(const string & original) {
return *(new string(original + this->suffix));
}
};
void dumpList(const list & list) {
copy(list.begin(), list.end(), ostream_iterator (cout, “n”));
}
void insertNewNodes(char c) {
cout
<< "entering makeNewNodes() with a character in the original input — "
<< c << "n";
transform(abbreviations.begin(), abbreviations.end(), front_inserter(
abbreviations), suffixAdder(c));
//dumpList(abbreviations);
}
void checkDupe(char c) {
if (!uniqueChars.insert(c).second) {
// insert returns a pair, whose second field indicates whether insert happened
cout <<"Error: duplicate character : "<<c; // insert skipped due to dupe
cin.get();
exit(0);
}
}
/* first pass scans in O(n) input array for duplicate characters.
* 2nd pass re-scans the input array and generates new abbreviations based on the existing population of abbreviations.
Suppose our 2nd scan is on the 4th character “x”
** Pre-condition: all existing abbrevations don't contain “x”
** Post-condition: all new abbreviations generated end in “x”
Number of abbreviations is 2 to the power of n (actually 1 fewer), therefore O(2 to the power of n)
This algorithm is iterative and more efficient than recursion. For a 200-character string, recursion would build a 200-frame stack.
*/
int main(int argc, char *argv[]) {
//string input = “gfedba21”; // testing
string input = string(argv[1]);
for_each(input.begin(), input.end(), checkDupe);
cout << "—no dupe found. Now generating abbreviations—n";
abbreviations.push_back(“”);
for_each(input.begin(), input.end(), insertNewNodes);
abbreviations.erase(remove(abbreviations.begin(), abbreviations.end(), “”),
abbreviations.end());
dumpList(abbreviations);
cout << "Total # of abbreviations = " << abbreviations.size();
cin.get();
}