c++ - STL算法中排序函数的问题

标签 c++ stl

我写了那几行:

#include <vector>
#include <algorithm>
#include <stdlib.h>
#include <time.h>
using namespace std;

template <class T> struct First
{
    T num;

    First() {}

    First(const T &a) : num(a) {}
};

 template <typename var> bool criterio(First<var> &primo, First<var> &secondo)
 {
    return (primo.num < secondo.num);
 }

int main()
 {
    vector< First<int> > f;

    srand (time(NULL));
    for(int i=0; i<20; i++) f.push_back( First<int>(rand() % 20) );

    sort(f.begin(),f.end(),criterio);

    return 0;
 }

我用“g++ program2.C”编译,答案是:

program2.C: 在函数‘int main()’中:

program2.C:28: error: no matching function for call to‘sort(__gnu_cxx::__normal_iterator*, std::vector, std::allocator > > > , __gnu_cxx::__normal_iterator*, std::vector, std::allocator > > >, unresolved overloaded function type)’

我不知道这是什么问题...你能帮我吗??

感谢帮助...

最佳答案

criterio 是一个模板,所以你需要给出模板化的类型:

   sort(f.begin(),f.end(),criterio<int>)

并且 criterio 函数必须将 const 引用作为参数:

 template <typename var> bool criterio(const First<var> &primo, 
                                         const First<var> &secondo)
  {
     return (primo.num < secondo.num);
  }

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

相关文章:

c++ - 了解每月第一天功能的代码

c++ - 如何在 C++ 中将转换应用于 STL 映射

c++ - 从 STL 容器中移除一些东西而不解构它

c++ - 无限等待条件变量

c++ - SendMessage(hwnd, registeredmssghere, 0, 1) 收到但未被发送到的 Hook 线程正确识别!

c++ - 如何有效地检查/限制 sqlite 数据库的大小?

c++ - 将 new 用于结构 C++ 时出现 Bad_alloc 异常

c++ - 热衷于在专门的模板代码中初始化静态常量成员?

c++ - 用于返回集合的所有子集的适当数据结构

c++ - 使用 C++/STL 将 std::vector<CString> 展平为 multi_sz 的推荐方法是什么