在priority_queue模板中c ++编译错误

时间:2013-11-29 04:52:11

标签: c++ templates

我有以下类喜欢在priority_queue中使用:

class People
{
public  :
    People(int iage,char *n)
    {
        age = iage ;
        strcpy(name,n) ;
    }
    bool operator >(People& m)
    {
        return( (this->age) >  m.getage() ) ;
    }
    int getage() {return age;}
    char* getname() {return name;}
private :
    int age ;
    char name[28] ;
} ;

priority_queue如:

template <typename T>
class Compare{
public:
    bool operator()(const pair<T,int> &lhs,const pair<T,int> &rhs) const{
       //return ((lhs.first) > (rhs.first)) ;
       T t1 = lhs.first ;
       T t2 = rhs.first ;
       return (t1 > t2) ;
   }
} ;

template <typename T>
vector<T> merge_arrays(const vector<vector<T> > &S)
{
    priority_queue<pair<T,int>,vector<pair<T,int> >,Compare<T> > min_heap;
    ......
}

在main()中:

int main()
{
    vector<People> v1 ;
    vector<People> v2 ;
    vector<People> v3 ;
    vector<vector<People> > vx ;
    char namex[3][20] = {"People1","People2","People3"} ;

    for(int idx=0;idx<30;idx++)
    {
        if( (idx%3)==0)
            v1.emplace_back(idx,namex[0]) ;
        else if( (idx%3)==1)
            v2.emplace_back(idx,namex[1]) ;
        else
            v3.emplace_back(idx,namex[2]) ;
    }//for

    vx.push_back(v1) ;
    vx.push_back(v2) ;
    vx.push_back(v3) ;

    vector<People> v = merge_arrays<People>(vx) ;
    ....
}

问题出在比较中,原始来源是:

template <typename T>
class Compare{
public:
    bool operator()(const pair<T,int> &lhs,const pair<T,int> &rhs) const{
       return ((lhs.first) > (rhs.first)) ;
   }
} ;

这会有编译错误,所以我将此源更改为以下内容并运行!!

template <typename T>
class Compare{
public:
    bool operator()(const pair<T,int> &lhs,const pair<T,int> &rhs) const{
       T t1 = lhs.first ;
       T t2 = rhs.first ;
       return (t1 > t2) ;
   }
} ;

虽然问题已经消失,但我仍然想知道我能为此次测试做些什么 所以不需要T t1 = lhs.first;并且T t2 = rhs.first;并且仍然使这个功能有效!!!!

任何评论,建议都表示赞赏!!

1 个答案:

答案 0 :(得分:2)

您的运算符不是const,也不是其参数。两者都需要。

注意传递给比较器的对象类型:

const std::pair<T,int>& lhs, const std::pair<T,int>& rhs

lhs.first > rhs.first仅在operator >也是const时有效。像这样声明你的运营商:

bool operator >(const People& m) const
{
    return age > m.age ;
}

另请注意,您的其他成员也可能是const,因为它们无意以任何方式修改对象。将它们声明为const可确保您在调用对象时不会意外地修改对象。即:

int getage() const { return age; }
const char* getname() const { return name; }

祝你好运。

相关问题