我有结构:
struct Node {
unsigned char symbol;
unsigned int freq;
Node* left;
Node* right;
Node(unsigned char _byte, int _freq)
: symbol(_byte), freq(_freq), left(nullptr), right(nullptr) {};
};
并且已经创建了这样的unordered_map
:
std::unordered_map<unsigned char, uint> freqs ={{'a',12}, {'b',122}};
我想做的-是通过以下方式创建priority_queue
:
freqs
中的每一对创建新节点priority_queue
个目录中创建Node
。到目前为止我尝试过的是: 从地图创建矢量,然后尝试创建priority_queue:
bool nodeCompare(const Node* first, const Node* second){
return first->freq > second->freq;
}
typedef std::priority_queue<Node*,
std::vector<Node*>,
nodeCompare()> my_queue;
std::vector<Node*> node_vect;
std::unordered_map<byte, uint>::iterator it;
for (it = freqs.begin(); it != freqs.end(); ++it)
{
Node* new_node = new Node(it->first, it->second);
node_vect.push_back(new_node);
}
my_queue(node_vect.begin(), node_vect.end(), nodeCompare);
但这不起作用:typedef
构造错误:
函数“ nodeCompare”不是类型名称
其他问题: 如果我以这种方式创建矢量,也许有某种方法可以将Node推入my_queue而不创建其他矢量?
my_queue q;
std::vector<Node*> node_vect;
std::unordered_map<byte, uint>::iterator it;
for (it = freqs.begin(); it != freqs.end(); ++it)
{
Node* new_node = new Node(it->first, it->second);
node_vect.push_back(new_node);
//q.push(new_node); this doesn't work
}
答案 0 :(得分:2)
priority_queue模板参数不希望函数,而是对象类型
template <class T, class Container = vector<T>,
class Compare = less<typename Container::value_type> > class priority_queue;
所以只需将该函数包装到struct / class(Functor)中,它应该可以工作。
struct Comparator
{
bool operator()(const Node* first, const Node* second) const {
return first->freq > second->freq;
}
};
typedef std::priority_queue<Node*,
std::vector<Node*>,
Comparator> my_queue;
如果要在“节点”结构内添加比较器,只需创建一个内部结构
struct Node {
unsigned char symbol;
unsigned int freq;
Node* left;
Node* right;
Node(unsigned char _byte, int _freq)
: symbol(_byte), freq(_freq), left(nullptr), right(nullptr) {};
struct Comparator
{
bool operator()(const Node* first, const Node* second) const {
return first->freq > second->freq;
}
};
};
typedef std::priority_queue<Node*,
std::vector<Node*>,
Node::Comparator> my_queue;
my_queue queue(node_vect.begin(), node_vect.end());