0
還有就是我的程序,它說明了可以用作分揀的STL容器實例作謂語模板:STL:指針關聯分類容器:排序謂詞模板
#include <iostream>
#include <set>
#include <iterator>
#include <algorithm>
#include <functional>
#include <string>
using namespace std;
template<typename T, template <typename> class comp = std::less> struct ComparePtr: public binary_function<T const *, T const *, bool> {
bool operator()(T const *lhs, T const *rhs) const {
comp<T> cmp;
return (cmp(*lhs, *rhs));
}
};
int wmain() {
string sa[] = {"Programmer", "Tester", "Manager", "Customer"};
set<string *, ComparePtr<string>> ssp;
for (int i(0) ; i < sizeof sa/sizeof sa[0] ; ++i)
ssp.insert(sa + i);
for_each(ssp.begin(), ssp.end(), [](string *s){ cout << s->c_str() << endl; });
return 0;
}
請,專注於謂語:這是正確寫入? 是否很好實例化comp
?有沒有一種方法可以不實例化comp
謂詞?
「*爲什麼要使用模板模板*」因爲它不需要人們說出'T'的類型,而您的方法卻是這樣。 C.F. http://ideone.com/jvTnm其中所需要的只是'ComparePtr <>',沒有指定其他內容。 – ildjarn 2012-01-09 23:35:12
@ildjarn有道理。儘管OPs代碼並非如此,所以我從來沒有考慮過它。你能把它作爲答案發布嗎?之後我會刪除我的答案。 – pmr 2012-01-09 23:43:45
我很好,你編輯你的答案,任何方式都沒有什麼大不了的。 : - ] – ildjarn 2012-01-09 23:50:39