使用自定義std :: set比較器我試圖將一組整數(shù)中的項的默認順序更改為lexicographic而不是numeric,并且我無法使用g ++進行以下編譯:file.cpp:bool lex_compare(const int64_t &a, const int64_t &b) {
stringstream s1,s2;
s1 << a;
s2 << b;
return s1.str() < s2.str();}void foo(){
set<int64_t, lex_compare> s;
s.insert(1);
...}我收到以下錯誤:error: type/value mismatch at argument 2 in template parameter list for ‘template<class _Key, class _Compare, class _Alloc> class std::set’error: expected a type, got ‘lex_compare’我究竟做錯了什么?
3 回答

哈士奇WWW
TA貢獻1799條經(jīng)驗 獲得超6個贊
您正在使用一個函數(shù),因為您應(yīng)該使用仿函數(shù)(一個重載()運算符的類,因此可以像函數(shù)一樣調(diào)用它。
struct lex_compare { bool operator() (const int64_t& lhs, const int64_t& rhs) const { stringstream s1, s2; s1 << lhs; s2 << rhs; return s1.str() < s2.str(); }};
然后使用類名作為類型參數(shù)
set<int64_t, lex_compare> s;
如果你想避免仿函數(shù)樣板代碼,你也可以使用函數(shù)指針(假設(shè)lex_compare
是一個函數(shù))。
set<int64_t, bool(*)(const int64_t& lhs, const int64_t& rhs)> s(&lex_compare);

楊魅力
3.使用struct with
TA貢獻1811條經(jīng)驗 獲得超6個贊
1.現(xiàn)代C ++ 11解決方案
auto cmp = [](int a, int b) { return ... };std::set<int, decltype(cmp)> s(cmp);
我們使用lambda函數(shù)作為比較器。像往常一樣,比較器應(yīng)該返回布爾值,指示作為第一個參數(shù)傳遞的元素是否被認為是在它定義的特定嚴(yán)格弱順序中的第二個之前。
2.與第一種解決方案類似,但功能代替lambda
使比較器成為通常的布爾函數(shù)
bool cmp(int a, int b) { return ...;}
然后使用它
std::set<int, decltype(&cmp)> s(&cmp);
3.使用struct with ()
operator的舊解決方案
struct cmp { bool operator() (int a, int b) const { return ... }};// ...// laterstd::set<int, cmp> s;
4.替代解決方案:從布爾函數(shù)創(chuàng)建struct
采取布爾函數(shù)
bool cmp(int a, int b) { return ...;}
并使用它來構(gòu)建struct std::integral_constant
#include <type_traits>using Cmp = std::integral_constant<decltype(&cmp), &cmp>;
最后,使用struct作為比較器
std::set<X, Cmp> set;

泛舟湖上清波郎朗
TA貢獻1818條經(jīng)驗 獲得超3個贊
Yacoby的回答激勵我編寫一個用于封裝仿函數(shù)樣板的適配器。
template< class T, bool (*comp)( T const &, T const & ) >class set_funcomp { struct ftor { bool operator()( T const &l, T const &r ) { return comp( l, r ); } };public: typedef std::set< T, ftor > t;};// usagebool my_comparison( foo const &l, foo const &r );set_funcomp< foo, my_comparison >::t boo; // just the way you want it!
哇,我覺得那值得一試!
- 3 回答
- 0 關(guān)注
- 912 瀏覽
添加回答
舉報
0/150
提交
取消