简体   繁体   English

stl排序比较类函数

[英]stl sort comparison class function

I'd like to use stl sort with a class comparison function greater that uses infoVec1 and infoVec2 but I'm getting a compile error: 我想将stl排序与greater的类比较函数一起使用,该类比较函数使用infoVec1infoVec2但是出现编译错误:

Here is the class header 这是类头

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);
};

I've initialized Compare in main like so: 我已经像这样在main中初始化了Compare:

Compare C = Compare(info1, info2);

And I'm trying to use great in main like: 而且我正在尝试使用main主要方法:

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

And I'm getting this error: 我收到此错误:

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

How could I fix this class so that greater will work with stl sort? 我如何解决这个问题,以便greater可以与stl sort一起使用?

Its easier to change the greater() method into operator()(). 将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);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM