c++ - STL排序比较类函数

标签 c++ sorting stl vector

我想将 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 C = Compare(info1, info2);

我正在尝试在 main 中使用 great,例如:

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

关于c++ - STL排序比较类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9798127/

相关文章:

c++ - 无法理解术语 'static'

c++ - 无法解析的外部符号C++-错误的声明?

c++ - 在 C++ 中使用 multimap 类创建数据库类

c++ - STL::带有原始指针的迭代器

用于高性能 FIFO 的 C++ 容器

c++ - typedef std::runtime_error MyError 与类 MyError:public std::runtime_error

c++ - 返回对类的引用

python - 对巨大的矩阵进行排序,然后在列表中找到最小的元素及其索引

java - 如何比较列表中的两个整数?

php - 如何对包含对象的 3 维数组进行排序?