I'm learning priority scheduling algorithm and trying to implement it using std::vector
. But the current performance of my code that's partially implemented is not that good since I'm performing sort
operation every time I add a new process to std::vector
list. Can somebody suggest ways I can improve my current partially implemented algorithm. This is my code:
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
void print_list(const std::vector<std::pair<int, int>>& pair_list) {
for (const auto& pa : pair_list)
std::cout << "process_ID: " << pa.first << ", " << "priority: " << pa.second << "\n";
std::cout << std::endl;
}
void add_pro(int pro_ID, int pro_pri, std::vector<std::pair<int, int>>& pair_list) {
pair_list.emplace_back(pro_ID, pro_pri);
std::sort(pair_list.begin(), pair_list.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b) {
return a.second < b.second;
});
}
bool check_pro_is_present(int pro_ID, const std::vector<std::pair<int, int>>& pair_list) {
for (const auto& pa : pair_list) {
if (pa.first == pro_ID)
return true;
}
return false;
}
bool is_higher_pri_pro_present(int pro_ID, const std::vector<std::pair<int, int>>& pair_list) {
if (pair_list.front().first == pro_ID)
return false;
return true;
}
int main() {
std::vector<int> process_ID_list { 1345, 45, 5646, 52525, 55757, 23424, 68696, 55878, 667, 252 };
std::vector<int> process_pri_list { 41, 334, 747, 41, 47, 7, 75, 544, 42, 6 };
std::vector<std::pair<int, int>> pair_list;
for (int i = 0; i < process_ID_list.size(); ++i) {
int new_pro_ID = process_ID_list.at(i);
int new_pro_pri = process_pri_list.at(i);
if (!check_pro_is_present(new_pro_ID, pair_list))
add_pro(new_pro_ID, new_pro_pri, pair_list);
else
std::cout << "process is already in list" << std::endl;
print_list(pair_list);
}
int query_pro_ID = 1345;
std::cout << std::boolalpha << is_higher_pri_pro_present(query_pro_ID, pair_list) << std::endl;
return (EXIT_SUCCESS);
}
std::priority_queue
. \$\endgroup\$std::priority_queue
. \$\endgroup\$vector
withmake_heap
,pop_heap
(etc.) will be more amenable to your needs. \$\endgroup\$std::set
?. Do you think it has better performance overstd::vector
in this case scenario? \$\endgroup\$set
, each node is dynamically allocated, so a lot here depends on how fast the allocator is (but it's probably at least worth a try). \$\endgroup\$