/* Lecture code 7.2
 *
 * Storing C strings in a set using a functor.
 * In case you're wondering why this would ever be useful, think about cases where we need to copy subsets of the set multiple times.
 * Using C strings, the copy is lightning fast (since we just copy a pointer, don't even need to duplicate the C string).
 */

#include <iostream>
#include <set>
#include <cstring>
#include <string>
#include <fstream>
#include <algorithm>
using namespace std;

const int MAX_LENGTH = 256;

/* Functor class to compare two C strings. */
class CppStrCmp
{
public:
	bool operator() (const char *one, const char *two) const
	{
		return strcmp(one, two) < 0; // Let strcmp do the work!
	}
};

typedef set<char *, CppStrCmp> CStrSet; // C String set.  Typedef is your friend here.

void LoadStrings(CStrSet &cStringSet)
{
	ifstream input("dictionary.txt");
	
	/* The code here uses the member function istream::getline.  Unlike the free function getline, istream::getline uses
	 * C strings since it predates the C++ string class.  It's very unsafe, but since we're using C strings it's okay.
	 */
	char line[MAX_LENGTH];
	while(input.getline(line, MAX_LENGTH))
	{
		/* Read the string and duplicate it. */
		char *cStringEquiv = new char[strlen(line) + 1];
		strcpy(cStringEquiv, line);
		cStringSet.insert(cStringEquiv);
	}
}

void DeallocateStrings(CStrSet &cStringSet)
{
	/* Call delete[] on all the elements.  This frees the memory - it's not removing elements from the set. */
	for(CStrSet::iterator itr = cStringSet.begin(); itr != cStringSet.end(); ++itr)
		delete [] *itr;
}

int main()
{
	CStrSet cStringSet;
	LoadStrings(cStringSet);

	/* Do work with C strings. */

	DeallocateStrings(cStringSet);
	
	return 0;
}