Last active
December 16, 2022 18:30
-
-
Save aprotyas/4523a93ff8b4d83fb6f068257db21cf7 to your computer and use it in GitHub Desktop.
Indexable priority queue (C++17)
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 <initializer_list> | |
#include <queue> | |
#include <vector> | |
template <typename T, typename Cmp> | |
struct indexable_queue : public std::priority_queue<T, std::vector<T>, Cmp> | |
{ | |
T& at(std::size_t index) { return this->c.at(index); } | |
const T& at(const std::size_t index) const { return this->c.at(index); } | |
indexable_queue() = default; | |
indexable_queue(std::initializer_list<T> items, Cmp cmp = Cmp{}) | |
: std::priority_queue<T, std::vector<T>, Cmp>(cmp, std::vector<T>{items}) {} | |
}; |
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 "indexable_pq.hpp" | |
#include <string> | |
#include <tuple> | |
struct Item{ | |
int price; | |
std::string name; | |
}; | |
struct ItemCmp{ | |
bool operator()(const Item& lhs, const Item& rhs) const { | |
return std::tie(lhs.price, lhs.name) > std::tie(rhs.price, rhs.name); | |
} | |
}; | |
int main() { | |
indexable_queue<Item, ItemCmp> items({{10, "Pizza"}, {5, "Coffee"}, {20, "Chocolate"}}); | |
for (std::size_t index {0UL}; index < items.size(); ++index) | |
{ | |
std::cout << items.at(index).name << '\n'; | |
} | |
/* | |
output: | |
Coffee | |
Pizza | |
Chocolate | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment