【问题标题】:problem with sort function in STL algorithmSTL算法中的排序函数问题
【发布时间】:2011-01-11 11:28:15
【问题描述】:

我已经写了那几行:

#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 > > >,未解析的重载函数类型)'

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

感谢您的帮助...

【问题讨论】:

    标签: c++ stl


    【解决方案1】:

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

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

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

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

    【讨论】:

    • @Kornel 对不起,我没听懂。
    • @Neil,忽略这一点——MSVC 是一个不符合标准的编译器(在没有 const 的情况下工作)就是老生常谈了:>。 Comenau online 正确地将缺少 const 视为错误。
    【解决方案2】:
    sort(f.begin(),f.end(),criterio<int>);
    

    您需要明确说明您正在使用的功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-25
      • 2011-01-27
      相关资源
      最近更新 更多