Skip to content

Instantly share code, notes, and snippets.

@AhmedSamara
Last active April 5, 2022 18:04
Show Gist options
  • Save AhmedSamara/a315883f0a14677c8594d8e2ff02f9d2 to your computer and use it in GitHub Desktop.
Save AhmedSamara/a315883f0a14677c8594d8e2ff02f9d2 to your computer and use it in GitHub Desktop.
A queu that ensures elements are unique before inserting them.
#include <unordered_set>
#include <queue>
#include <assert.h>
#include <stdexcept>
template <class T>
class UniqueQueu {
public:
bool empty() {
// sanity check. Either both empty or both not empty.
assert(q.empty() == elems.empty());
return q.empty();
}
T front() {
return q.front();
}
T pop_front() {
if(q.empty()) std::runtime_error("Error: popping from empty Q\n");
T victim = q.front();
elems.erase(victim);
q.pop();
return victim;
}
void push_back(T arg) {
// add if not exist.
if(elems.find(arg) == elems.end()) {
q.push(arg);
elems.insert(arg);
}
}
private:
std::unordered_set<T> elems;
std::queue<T> q;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment