繁体   English   中英

stl排序比较类函数

[英]stl sort comparison class function

我想将stl排序与greater的类比较函数一起使用,该类比较函数使用infoVec1infoVec2但是出现编译错误:

这是类头

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

我已经像这样在main中初始化了Compare:

Compare C = Compare(info1, info2);

而且我正在尝试使用main主要方法:

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一起使用?

将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