Last active
April 5, 2022 18:04
-
-
Save AhmedSamara/a315883f0a14677c8594d8e2ff02f9d2 to your computer and use it in GitHub Desktop.
A queu that ensures elements are unique before inserting them.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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