So I kinda know that I can't make a priority queue with type struct but I don't exactly understand the reason why? I mean if you can create template classes to make your own type, why would a struct be any different?
This is what my code looks like in main.cpp:
#include <iostream>
#include <queue>
#include <string>
struct DATA {
std::string key;
int data;
};
int main() {
std::priority_queue<DATA> priorityQ;
DATA newItem;
newItem.key = "apples";
newItem.data = 3;
priorityQ.push(newItem);
std::cout << priorityQ.top().key << std::endl;
std::cout << "Press the 'ENTER' key to continue...";
std::cin.get();
return 0;
}
The error come up with:
Error C2678 binary '<': no operator found which takes a left-hand
operand of type 'const DATA' (or there is no acceptable conversion)
TestProj c:\program files (x86)\microsoft visual studio
14.0\vc\include\xstddef Line: 240
I tried making this operator overload:
bool operator<(const DATA& a, const DATA& b) {
return a.data > b.data;
}
But it still does not compile...
My question is: is it possible to put struct objects in priority queues and , and if not, why?
Here you go.
#include <iostream>
#include <queue>
#include <string>
struct DATA {
std::string key;
int data;
// EITHER THIS
bool operator<(const DATA & d2) const {return <your logic here>;}
};
// OR THIS
bool operator<(const DATA &d1, const DATA & d2){return <your logic here>;}
int main() {
std::priority_queue<DATA> priorityQ;
DATA newItem;
newItem.key = "apples";
newItem.data = 3;
priorityQ.push(newItem);
std::cout << priorityQ.top().key << std::endl;
std::cout << "Press the 'ENTER' key to continue...";
std::cin.get();
return 0;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments