stl sort比较类函数

时间:2012-03-21 03:11:23

标签: c++ sorting stl vector

我想将stl sort与使用greaterinfoVec1的类比较函数infoVec2一起使用但是我遇到了编译错误:

这是类标题

class Compare{
    Compare();
    std::vector< std::vector<std::string> >& infoVec1;
    std::vector< std::vector<std::string> >& infoVec2;


    public:

    bool greater(int one, int two);

    Compare(std::vector< std::vector<std::string> >& info1,
    std::vector< std::vector<std::string> >& info2);
};

我已经初始化了像这样的比较:

Compare C = Compare(info1, info2);

我正试图在主要方面使用伟大的:

sort(vec.begin(), vec.end(), C.greater);

我收到了这个错误:

main.cpp:266: error: no matching function for call to ‘sort(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, <unresolved overloaded function type>)’
/usr/include/c++/4.2.1/bits/stl_algo.h:2852: note: candidates are: void std::sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, _Compare = bool (Compare::*)(int, int)]
make: *** [main.o] Error 1

我如何修复此类,以便greater可以使用stl sort?

1 个答案:

答案 0 :(得分:1)

更容易将greater()方法更改为operator()()。

class Compare{
    Compare();
    std::vector< std::vector<std::string> >& infoVec1;
    std::vector< std::vector<std::string> >& infoVec2;


    public:

    bool operator()(int one, int two) const;  // this is used automatically.

    Compare(std::vector< std::vector<std::string> >& info1,
    std::vector< std::vector<std::string> >& info2);
};