[英]STL: pointer associative sorted container: sorting predicate template
我的程序演示了謂詞模板,該模板可用作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
謂詞?
為什么要完全使用模板模板,而不僅僅是在通用二進制比較器周圍添加簡單的包裝器?
template<typename P>
struct PointerPred {
P p;
template<typename T>
bool operator()(const T& x, const T& y) { return p(*x, *y); }
};
Boost Pointer容器也可以使此操作變得容易得多。
Ildjarn展示了如何正確實現函子:
template<template<typename> class comp = std::less>
struct ComparePtr {
template<typename T>
bool operator()(T const *lhs, T const *rhs) const {
return comp<T>()(*lhs, *rhs);
}
};
這樣,就不再需要指定參數的類型。
編輯:在我的代碼中曾經有std::forward
和rvalue引用,這絕對沒有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.