#include <utility>
#include<unordered_map>
#include<queue>
using namespace std;
struct Task {
char t;
int cnt;
Task(char ch, int cnt):t(ch), cnt(cnt){};
};
struct CompTask {
bool operator() (const unique_ptr<Task>& a, const unique_ptr<Task>& b) {
return a->cnt < b->cnt;
}
};
class Schedule {
public:
int schedule() {
unordered_map<unique_ptr<Task>, int> sleep_q;
priority_queue<unique_ptr<Task>, vector<unique_ptr<Task>>, CompTask> ready_q; // max heap
ready_q.push(std::make_unique<Task>('A', 1));
auto& ptr = ready_q.top();
//sleep_q.insert({ptr, 1}); // compile error
sleep_q.insert({std::move(ptr), 1}); // compile error
// some other code...
return 1;
}
};
int main() {
return 0;
}
// error:
cpp:38:17: error: no matching member function for call to 'insert'
sleep_q.insert({std::move(ptr), 1}); // compile error
~~~~~~~~^~~~~~
Programming context: I had a task class and the program attempts to simulate the task scheduling (which involves moving a task back and forth between a ready queue and a sleep queue). I have two STL containers for ready queue and sleep queue respectively, the priority_queue has value type unique_ptr<Task>, the other is unorder_map (sleep queue) whose key is also unique_ptr<Task>. I had trouble moving the unique_ptr object from priorty_queue to unordered_map (shown in the code).
My questions are: (1) how to insert an item into the unordered_map, I had compilation errors on doing that. (2) in the problem context, which type of "pointer" would be preferred? unique_ptr<Task>, shared_ptr<Task>, or just Task*
Aucun commentaire:
Enregistrer un commentaire