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

标签 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 ;并且仍然使这个功能起作用 !!!!

如有任何意见,建议,我们将不胜感激!!

最佳答案

你的运算符不是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 可确保您在调用它们时不会意外修改对象。即:

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

祝你好运。

关于priority_queue模板中的c++编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20278584/

相关文章:

C++:忽略候选模板:模板参数的显式指定参数无效

c++ - 非源文件更改时触发构建

c++ - 使用 ffmpeg 进行 YUV 到 JPG 编码

c++ - 在类模板中存储可变参数

c++ - 在现代 C++ 中使用 try..catch block 通过模板元编程包装任意函数调用

c++ - 无法在 C++ 服务器应用程序上归档 iphlpapi.lib

c++ - strstr 在 codeforces 上的 C++ 4.7 中不起作用

c++ - 模板和结构的混合

c++ - 如何在 Qt Creator 项目向导中添加自定义构建步骤?

c++ - 构造函数中的段错误,但仅限于某些模板参数