【问题标题】:stl sort comparison class functionstl排序比较类函数
【发布时间】:2012-03-21 03:11:22
【问题描述】:

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

这是类头

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

【问题讨论】:

  • 比较函数应该是独立函数或者函数对象。
  • vec 的类型为 std::vector

标签: c++ sorting stl vector


【解决方案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);
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2012-05-27
    • 1970-01-01
    相关资源
    最近更新 更多