// Course: CS 141 // Lecture Section: Enter your lecture section number here (1, 2) // Lab Section: Enter your lab section number here (21, 22, 23) // Assignment #: 1 // First Name: Enter your FIRST name here (eg, John) // Last Name: Enter your LAST name here (eg, Doe) // ID Number: Enter your ID number here (eg, 12-345-678) // Email address: Enter your UCR email address here (eg, jdoe@cs.ucr.edu) // ======================================================================= //AssocList.cc #ifndef _ASSOCLIST_CC #define _ASSOCLIST_CC #include #include "AssocList.h" #include "Comparisons.h" #include "Array.cc" // destructor template AssocList::~AssocList() { } // constructors template AssocList::AssocList() : use_default(0) { } template AssocList::AssocList(VALUE const & def) : use_default(1), default_init(def) { } template AssocList::AssocList(AssocList const & a) : pairs(a.pairs), use_default (a.use_default), default_init (a.default_init) { } // operator= template AssocList& AssocList::operator=(const AssocList& a) { pairs = a.pairs; // deep copy use_default = a.use_default; default_init = a.default_init; return *this; } // find template int AssocList::find(KEY const & k) const { for (int i = 0; i < pairs.size(); ++i) if (! pairs[i].removed && Equal(pairs[i].k, k)) return i; return -1; } // clear template void AssocList::clear() { pairs.clear(); } // find template int AssocList::exists(KEY const & k) const { int i = find(k); return i != -1 && pairs[i].removed == 0; } // remove template void AssocList::remove(KEY const & k) { int i = find(k); if (i == -1) return; pairs[i].removed = 1; } // operator[] and const operator[] template VALUE & AssocList::operator[](KEY const & k) { int i = find(k); if (i >= 0) return pairs[i].v; // find next free pair pointer for (i = 0; i < pairs.size() && ! pairs[i].removed; ++i) ; // insert pair for key k and return v pairs[i].k = k; if (use_default) pairs[i].v = default_init; pairs[i].removed = 0; return pairs[i].v; } template VALUE AssocList::operator[](KEY const & k) const { int i = find(k); if (i >= 0) return pairs[i].v; std::cerr << "AssocList index out of range\n"; exit(1); } // keys() and values() template Array AssocList::keys() const { Array a; for (int i = 0; i < pairs.size(); ++i) if (! pairs[i].removed) a[a.size()] = pairs[i].k; return a; } template Array AssocList::values() const { Array a; for (int i = 0; i < pairs.size(); ++i) if (! pairs[i].removed) a[a.size()] = pairs[i].v; return a; } // operator<< template std::ostream & operator<<(std::ostream & out, const AssocList & a) { // out << "use_default = " << a.use_default; // if (a.use_default) { // out << ", default = " << a.default_init; // } // out << "\npairs = ["; out << "["; for (int i = 0; i < a.pairs.size(); ++i) { if (i != 0) out << ", "; out << "(" << a.pairs[i].k << ", " << a.pairs[i].v << ", " << a.pairs[i].removed << ")"; } out << "]"; return out; } #endif