Skip to content

Instantly share code, notes, and snippets.

@aprotyas
Last active December 16, 2022 18:30
Show Gist options
  • Save aprotyas/4523a93ff8b4d83fb6f068257db21cf7 to your computer and use it in GitHub Desktop.
Save aprotyas/4523a93ff8b4d83fb6f068257db21cf7 to your computer and use it in GitHub Desktop.
Indexable priority queue (C++17)
#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}) {}
};
#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