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
谓词?
There is my program that illustrates predicate template that could be used as sorting predicate for STL containers instantiation:
#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;
}
Please, focus on predicate: is it written correctly?
Is it good to instantiate comp
? Is there a way that allows not to instantiate comp
predicate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么要使用模板 template 而不仅仅是在通用二进制比较器周围添加一个简单的包装器?
Boost 指针容器也可以使这一点变得很多更轻松。
Ildjarn 展示了如何正确实现函子:
这样就不再需要指定参数的类型。
编辑:我的代码中曾经有 std::forward 和右值引用,这完全没有意义。
Why use a template template at all and not just add a simple wrapper around general binary comparators?
Boost Pointer Containers could also make this a lot easier.
Ildjarn showed how to implement your functor correctly:
This way it isn't necessary to specify the type of the arguments anymore.
Edit: There used to be
std::forward
and rvalue references in my code, which made absolutely no sense.