Skip to content

Instantly share code, notes, and snippets.

@zhhailon
Last active March 3, 2022 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhhailon/8afa8092269e26a6ddc34e7b7cf1ea5a to your computer and use it in GitHub Desktop.
Save zhhailon/8afa8092269e26a6ddc34e7b7cf1ea5a to your computer and use it in GitHub Desktop.
template <typename T> class ArraySet {
private:
T *items;
int count;
public:
/** Create an empty set. */
ArraySet() {
items = new T[100];
count = 0;
}
/** Destroy the set. */
~ArraySet() { delete[] items; }
/** Returns the number of values in set. */
int size() const { return count; }
/** Checks if x is in the set. */
bool contains(T x) {
// i: [0, count - 1]
for (int i = 0; i < count; i++) {
if (items[i] == x) {
return true;
}
}
return false;
}
/** Add x to the set if it is not in set. */
void add(T x) {
if (!contains(x)) {
// Copied from addLast in AList:
items[count] = x;
count++;
}
}
class iterator {
private:
/** Pointing to an item in the underlying array. */
T *ptr_;
public:
/** Constructor */
iterator(T *ptr) { ptr_ = ptr; }
T &operator*() { return *ptr_; }
iterator& operator++() {
this->ptr_ += 1;
return *this;
}
bool operator==(const iterator &rhs) { return this->ptr_ == rhs.ptr_; }
bool operator!=(const iterator &rhs) { return !(*this == rhs); }
};
/** Iterator whose pointer is pointing to the first value in items array. */
iterator begin() { return iterator(items); }
/** Iterator whose pointer is pointing to the memory box next to the last
* value in items array. */
iterator end() { return iterator(items + count); }
};
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "ArraySet.h"
#include <doctest.h>
#include <iostream>
#include <string>
using namespace std;
TEST_CASE("constructor and destructor and size") {
ArraySet<int> aset;
CHECK(aset.size() == 0);
ArraySet<string> aset2;
CHECK(aset2.size() == 0);
}
TEST_CASE("add and contains") {
ArraySet<int> aset;
aset.add(5);
aset.add(10);
aset.add(15);
aset.add(15); // this should do nothing
CHECK(aset.size() == 3);
CHECK(aset.contains(5) == true);
CHECK(aset.contains(25) == false);
}
TEST_CASE("iterator") {
ArraySet<int> aset;
aset.add(5);
aset.add(10);
aset.add(15);
aset.add(15); // this should do nothing
for (int i : aset) {
cout << i << endl;
}
ArraySet<int>::iterator it = aset.begin();
while (it != aset.end()) {
cout << *it << endl;
++it;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment