I am trying to learn C++ by solving some leetcode questions. The question link is https://leetcode.com/problems/design-movie-rental-system/. I tried running my solution but it keeps showing a huge red block of error. My code is shown below. The logic might not be completely right but I am completely stuck on how to properly pass comparator functions. I surrounded the declarations that are causing problems with ***. There are no compilation errors but it throws errors whenever insert happens and the comparator is used. I used a previous stackoverflow solution to write this syntax (Using custom std::set comparator)
class MovieRentingSystem {
public:
class Rental {
public:
int shop;
int price;
int movie;
Rental(int shop, int price, int movie) {
this->shop = shop;
this->price = price;
this->movie = movie;
}
static bool cmp(const Rental& a, const Rental& b) {
if (a.price != b.price) {
return a.price < b.price;
}
if (a.shop != b.shop) {
return a.shop < b.shop;
}
return a.movie < b.movie;
}
};
***unordered_map<int, set<Rental, decltype(&Rental::cmp)>> movieMap;
set<Rental, decltype(&Rental::cmp)> rented;***
unordered_map<int, int> *priceMap;
public:
~MovieRentingSystem() {
delete[] priceMap;
}
MovieRentingSystem(int n, vector<vector<int>>& entries) {
priceMap = new unordered_map<int, int>[n];
for (vector<int> entry : entries) {
if (movieMap.find(entry.at(1)) == movieMap.end()) {
movieMap[entry.at(1)] = set<Rental, decltype(&Rental::cmp)>();
}
priceMap[entry.at(0)][entry.at(1)] = entry.at(2);
movieMap[entry.at(1)].insert(Rental(entry.at(0), entry.at(2), entry.at(1)));
}
}
vector<int> search(int movie) {
vector<vector<int>> res = cheapest(movieMap[movie]);
vector<int> vec = vector<int>();
for (vector<int> v : res) {
vec.push_back(v.at(0));
}
return vec;
}
void rent(int shop, int movie) {
Rental rental = Rental(shop, priceMap[shop][movie], movie);
movieMap[movie].erase(rental);
rented.insert(rental);
}
void drop(int shop, int movie) {
Rental rental = Rental(shop, priceMap[shop][movie], movie);
rented.erase(rental);
movieMap[movie].insert(rental);
}
vector<vector<int>> report() {
return cheapest(rented);
}
vector<vector<int>> cheapest(set<Rental, decltype(&Rental::cmp)> &set) {
vector<vector<int>> res = vector<vector<int>>();
auto cur = set.begin();
for (int i = 0; i < 5 && cur != rented.end(); i++, cur++) {
vector<int> current = vector<int>();
current.push_back(cur->shop);
current.push_back(cur->movie);
current.push_back(cur->price);
res.push_back(current);
}
return res;
}
};
Error display:
vector<vector<int>> vec = vector<vector<int>>({{0, 1, 5}, {0, 2, 6}, {0, 3, 7}, {1, 1, 4}, {1, 2, 7}, {2, 1, 5}});
MovieRentingSystem system = MovieRentingSystem(10, vec);
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
I know this is a little overcomplicated for the problem but I want to know how to pass custom comparators properly and use them