storage templates
-
Hi just a quick question from a novice programmer. I want a storage class that only allows one instance of each thing like set myList; but I want the items to be kept in sequential order For example I want to add "John" to the set. Then I want to add "Peter". Then "Chris". Then I try and add "Peter" again it won't do it, so my set is still [John, Peter, Chris] and then it keeps them in the order I entered them so when I can ask for the second item I added I get "Peter. My understanding of set is when I insert a new member it will put it it alphabetical order. any ideas?? :)
-
Hi just a quick question from a novice programmer. I want a storage class that only allows one instance of each thing like set myList; but I want the items to be kept in sequential order For example I want to add "John" to the set. Then I want to add "Peter". Then "Chris". Then I try and add "Peter" again it won't do it, so my set is still [John, Peter, Chris] and then it keeps them in the order I entered them so when I can ask for the second item I added I get "Peter. My understanding of set is when I insert a new member it will put it it alphabetical order. any ideas?? :)
yeah, easy. Make a linked list, then upon adding a new item it gets added as a new node on the tail end of the list. A little something like this, though with UNICODE & c++ support. There's linked lists in the stl now, but linked lists are a good educational tool, imho - hence my recommendation to write some code that uses your own implementation of them at least once.
struct myListItem
{
char *itemText;
int origPos;
myListItem *nextItem;
myListItem *prevItem;
};// *****No error checking*******
// ** no code provided for initialization of list **
// checks a linked list for the provided text. If found, pointer to that item is returned
// if not found, the text is added to the list and a pointer to the new list item is returned
myListItem *add(myListItem *linkedListHead, char *newText)
{
myListItem *curItem;
bool alreadyExists = false;
int curItemNum = 0;curItem = linkedListHead; if (curItem != NULL) do { if (!strcmp(curItem->itemText, newText)) return curItem; curItem = curItem->nextItem; curItemNum++; }while (curItem->nextItem != NULL); else return NULL; // we were passed a NULL pointer instead of the head of a list. exit // create the new list item curItem->nextItem = (myListItem\*) malloc(1\*sizeof(myListItem)); // set it's prevItem member to point to us ,so we can traverse the list forwards or backwards curItem->nextItem->prevItem = curItem; // keep track of where the item was added. This means we can sort the list and still unsort it later curItem->origPos = curItemNum; // move to the new item curItem = curItem->nextItem; // allocate memory for the text curItem->itemText = (char\*) malloc(strlen(newText)+1); // copy the text strcpy(curItem->itemText, newText); // bugger off return curItem;
}