0
我想如下定義優先級隊列自定義比較:定義優先級隊列中的類中使用自定義比較函數
typedef bool (*comp)(int,int);
bool compare(int exp1,int exp2){
return (exp1 > exp2);
}
class test{
public:
priority_queue<int,vector<int>,comp> test_pq(compare); // Gives compilation error
};
int main()
{
priority_queue<int,vector<int>,comp> pq(compare); // Compiles perfectly
return 0;
}
這是編譯錯誤,顯示了
test.cpp:18:47: error: ‘compare’ is not a type
priority_queue<int,vector<int>,comp> test_pq(compare);
^
我也試過在測試類中聲明另一個比較函數,但沒有任何效果。爲什麼主函數中的優先級隊列不能編譯?定義一個比較專用的類是這裏唯一的工作嗎? 謝謝。
謝謝你的回覆:)但是,是不是有辦法讓它工作而不考慮版本?通過將初始化轉移到類構造器來說吧? –
@ ant_1618,是的,當然你可以做到這一點。我更新了包含這個變體的答案。但如果你已經知道單詞'initialization'和'constructor',我希望你應該已經知道一個答案...... =) – magras
我沒有意識到cpp的初始化成員變量的方式隱式地在構造函數中用'Test():[initialisation列表] {\\ code}'。所以,我無法想出這個答案:P 現在很清楚:D謝謝:) –