【发布时间】:2026-02-19 08:45:01
【问题描述】:
我目前正在尝试编写一个函数来对条目项的向量进行排序,这些项在我的头文件中定义。
struct Entry{
string word;
int count;
};
基本上,每个条目都有一个string 和一个int。我要做的是按每个条目的count 值按降序对vector<Entry> 进行排序。我尝试在 .cpp 文件中使用 std::sort:
bool intcomp(const Entry &lhs, const Entry &rhs){
return lhs.count < rhs.count;
}
void SortedByCount(std::ostream &out) const{
std::sort(vocabulary.begin(), vocabulary.end(), intcomp);
}
但是编译器随后会吐出一堵巨大的错误墙,比如这个
/usr/bin/../lib/gcc/x86_64-redhat-linux/4.8.3/../../../../include/c++/4.8.3/bits/stl_heap.h:247:12: note:
in instantiation of function template specialization
'std::__push_heap<__gnu_cxx::__normal_iterator<Entry *const *,
std::vector<Entry *, std::allocator<Entry *> > >, long, Entry *>'
requested here
std::__push_heap(__first, __holeIndex, __topIndex,
^
我很不知道该怎么做,所以任何指针都将不胜感激。
编辑:
头文件包含Entry的结构体及其构造函数,以及intcomp和SortedByCount(std::ostream &out) const的原型,而.cpp文件包含intcomp和SortedByCount(std::ostream &out) const的定义。我收到此错误:
reference to non-static member function must
be called
std::sort(vocabulary.begin(), vocabulary.end(), intcomp);
^
是因为intcomp() 方法不是静态的吗?或者还能是什么?再次感谢。
【问题讨论】:
-
从错误信息可以看出你的
vocabulary向量大概存储了指向Entry的指针,即std::vector<Entry*> -
你应该发一个MCVE。