#include "stdstuff.h" #include "IntSet.h" void IntSet::add (int value) { if (valueExists(value)) return; // value already in set if (count == MAXVALUES) { throw overflow_error ("IntSet::add - set overflow"); } data[count++] = value; walkInProgress = false; // scrub any ongoing walk return; } bool IntSet::remove (int value) { int i; for (i = 0; i < count; i++) { if (data[i] == value) { // we've found the data value. // overwrite it with the last data value and adjust the count // to reflect the fact that there are now one fewer values in // the set. note that this works even if the value being removed // is the last value in the set. data[i] = data[--count]; walkInProgress = false; // scrub any ongoing walk return true; } } return false; } void IntSet::removeAll () { count = 0; walkInProgress = false; } bool IntSet::valueExists (int value) const { int i; for (i = 0; i < count; i++) { if (data[i] == value) { return true; } } // value not found return false; } bool IntSet::startWalk (int &value) { if (count == 0) return false; walkInProgress = true; walkPosition = 0; value = data[walkPosition]; return true; } bool IntSet::continueWalk (int &value) { if (!walkInProgress) { throw range_error ("IntSet::continueWalk invalid call"); } if (++walkPosition == count) { walkInProgress = false; // we've come to the end of the road return false; } value = data[walkPosition]; return true; } bool IntSet::operator== (const IntSet &otherSet) const { int i; // if the sets have different sizes, they aren't equal if (count != otherSet.count) return false; // the sets have the same size. if all of the values in one of // them are in the other, they are equal. if any of the values in // one set is not in the other set, they are not equal. for (i = 0; i < count; i++) { if (!otherSet.valueExists(data[i])) return false; } return true; } IntSet IntSet::intersect (const IntSet &otherSet) const { IntSet result; int i; for (i = 0; i < count; i++) { // go through values in implicit set if (otherSet.valueExists(data[i])) { // if value also exists in other set, put it in result result.add(data[i]); } } return result; } IntSet IntSet::unionWith (const IntSet &otherSet) const { IntSet result = otherSet; // start with otherSet int i; for (i = 0; i < count; i++) { // add all values from implicit set result.add(data[i]); } return result; }