我正在努力更好地熟悉C ++模板编程。为了实践,我决定实现一个优先级队列字典模板类,其中包含底层的priority_queue和unordered_map。但是,当我尝试在我的MBP上使用clang ++编译我的程序时,会打印出一些我不理解的错误消息。
我的代码在一个名为pqDictTotal.cpp的文件中
#include <queue>
#include <unordered_map>
#include <string>
#include <iostream>
template <typename P, typename V>
class PQDict {
private:
std::priority_queue<P> *pq;
std::unordered_map<P, V> *m;
public:
int getSize() {
return this->pq->size();
}
bool isEmpty() {
return this->pq->empty();
}
V getMin() {
P priority = this->pq->top();
V value = this->m[priority];
return value;
}
P getMinPriority() {
return this->pq->top();
}
V removeMin() {
P priority = this->pq->pop();
V value = this->m[priority];
this->m->erase(priority);
return value;
}
void insert(P priority, V value) {
this->pq->push(priority);
this->m[priority] = value;
}
PQDict() {
this->pq = new std::priority_queue<P>();
this->m = new std::unordered_map<P, V>();
}
~PQDict() {
delete pq;
delete m;
}
};
int main() {
PQDict<int, std::string> mypq;
mypq.insert(23, "BDWF");
mypq.insert(0, "ABC");
mypq.insert(15, "SDFSDFL");
mypq.insert(3, "GHF");
mypq.insert(10, "LKSJDF");
int minp;
std::string mins;
while (!mypq.isEmpty()) {
minp = mypq.getMinPriority();
mins = mypq.removeMin();
std::cout << minp << ", " << mins << std::endl;
}
}
使用
编译时clang++ pqDictTotal.cpp
我得到了
pqDictTotal.cpp:51:23: error: no viable overloaded '='
this->m[priority] = value;
~~~~~~~~~~~~~~~~~ ^ ~~~~~
pqDictTotal.cpp:71:8: note: in instantiation of member function 'PQDict<int,
std::__1::basic_string<char> >::insert' requested here
mypq.insert(23, "BDWF");
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/unordered_map:829:20: note:
candidate function not viable: no known conversion from
'std::__1::basic_string<char>' to 'const std::__1::unordered_map<int,
std::__1::basic_string<char>, std::__1::hash<int>,
std::__1::equal_to<int>, std::__1::allocator<std::__1::pair<const int,
std::__1::basic_string<char> > > >' for 1st argument
unordered_map& operator=(const unordered_map& __u)
^
pqDictTotal.cpp:41:7: error: cannot initialize a variable of type 'int' with an
rvalue of type 'void'
P priority = this->pq->pop();
^ ~~~~~~~~~~~~~~~
pqDictTotal.cpp:83:17: note: in instantiation of member function 'PQDict<int,
std::__1::basic_string<char> >::removeMin' requested here
mins = mypq.removeMin();
^
2 errors generated.
为什么我需要重载= for unordered_map?用'void'类型的rvalue'初始化'int'类型的变量是什么意思?
非常感谢任何帮助。