这段代码编译通过,但是执行出问题,所以我就打了断点,发现代码跑到 // 1 这个地方就挂了。
这明明就是一句普通的map插入操作啊,怎么会出错呢,希望哪位能帮忙解答,不胜感激。
另外:// 1 处的代码我改为使用 insert 进行插入也挂了
struct greaterKey{
bool operator()(const map<string, int>::iterator &key1,
const map<string, int>::iterator &key2) {
return key1->second > key2->second;
}
};
vector<string> getAppearMostK(const vector<string> &sarr, int k) {
// 建立词频表
map<string, int> wordTable;
for(int i = 0; i < sarr.size(); ++i) {
if(wordTable.count(sarr[i]) == 0) {
wordTable[sarr[i]] = 0; // 1
}
else{
++wordTable[sarr[i]];
}
}
// 创建小根堆,以map<string, int>::iterator->second比较
priority_queue<map<string, int>::iterator,
vector<map<string, int>::iterator>,
greaterKey> smallQue;
// k个元素入队
int count = 0;
auto beg = wordTable.begin();
for(; beg != wordTable.end(); ++beg) {
smallQue.push(beg);
++count;
if(count == k) {
break;
}
}
// 剩下的元素入队一个,弹出一个,保证小根堆中存储的元素数量为K
// 最终遍历完毕,得到最大的k个元素
while(beg != wordTable.end()) {
++beg;
smallQue.push(beg);
smallQue.pop();
}
// 将结果写入ans
vector<string> ans;
while(!smallQue.empty()) {
ans.push_back(smallQue.top()->first);
smallQue.pop();
}
return ans;
}
gdb 调试的截图如下: