对C++中的对象进行排序
struct Keyword
{
std::string keyword;
int numUses;
};
bool sortingVector(const Keyword& key1, const Keyword& key2)
{
return key1.numUses < key2.numUses;
}
sort(topKeywords.begin(), topKeywords.end(), sortingVector);
: no matching function for call to 'sort(std::vector<Keyword>::iterator, std::vector<Keyword>::iterator, <unresolved overloaded function type>)'
c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/stl_algo.h:5236:18: note: candidate is: void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = __gnu_cxx::__normal_iterator<Keyword*, std::vector<Keyword> >, _Compare = bool (NewsAggregatorImpl::*)(const Keyword&, const Keyword&)]
为什么这不正确,我的编译器给了我那个错误。
而我希望我的功能是全球性的。
谢谢。对C++中的对象进行排序
是sortingVector
某个类的非静态成员?该错误消息表明,在这种情况下,您需要将其包装(例如,使用boost::bind
)到二进制操作中,该操作不需要参数this
。您可能想将sortingVector
改为静态成员或免费函数。
你可能想打电话std::sort
而不是纯粹的排序,可能必须包括适当的头文件(algorithm
,除非我错了)。
是的,我包括,看起来像我必须使该功能静态 – Kobe 2011-03-10 20:16:01
你using namespace std;
?如果不是你想要std::sort()
#include <vector>
#include <algorithm>
#include <string>
struct Keyword
{
std::string keyword;
int numUses;
};
bool sortingVector(const Keyword& key1, const Keyword& key2)
{
return key1.numUses < key2.numUses;
}
int main()
{
std::vector<Keyword> topKeywords(100);
// imagine topKeywords initialization here
std::sort(topKeywords.begin(), topKeywords.end(), sortingVector);
return 0;
}
编译我的机器上(GCC 4.4.3版)的罚款。
这是一个编译例子应该是什么样子:
因为你没有提供这是产生人都给予了几种不同类型的答案的错误确切的代码。因此,生成一个可编译的例子显示问题通常是一个好主意。
#include <algorithm>
#include <vector>
#include <string>
struct Keyword
{
std::string keyword;
int numUses;
};
bool sortingVector(const Keyword& key1, const Keyword& key2)
{
return key1.numUses < key2.numUses;
}
int main()
{
std::vector<Keyword> topKeywords;
std::sort(topKeywords.begin(), topKeywords.end(), sortingVector);
}
一般的编译器可以做优化的更好的工作(据我所知)如果你使用一个仿函数,而不是一个函数指针。
struct SortingVectorFunctor
{
bool operator()(const Keyword& key1, const Keyword& key2) const
{
return key1.numUses < key2.numUses;
}
};
...因为它会使用特定于你的函子类型的模板参数来实例化'std :: sort',它的'operator()'因此可以很容易地被内联到那个实例中。使用函数指针,std :: sort'的实例化仅用于函数指针类型,而不是用于确切的函数,因此内联调用指针实际指向的特定函数是一件比较困难的工作。它不能被内联到实例化中,只能被内联替换为实例化的调用。至少,这就是我所知道的;-) – 2011-03-10 20:39:46
但是,如果函数在编译时是固定的,那么我看不出该函数不能被内联的原因。编译器的麻烦是证明函数指针在运行时没有被修改,所以即使我们知道它没有改变,编译器也能证明它。 – 2011-03-10 23:28:58
你看不出为什么比较器不能内联到(比如说)'std :: sort
把std::
放在你的sort
的电话前面。和源文件顶部的#include <algorithm>
。
您有多个排序向量函数 - 因此您的错误的<unresolved overloaded function type>
部分。
是的,这是问题,我didint知道这一点。下次我会记住这一点,谢谢 – Kobe 2011-03-10 20:15:13