effective stl 第36条:理解copy_if的正确实现
来源:互联网 发布:优惠券制作软件 编辑:程序博客网 时间:2024/05/19 11:48
STL 中有11个包含了copy的算法:
copy
copy_backward
replace_copy_if
reverse_copy
replace_copy_if
unique_copy
remove_copy
rotate_copy
remove_copy_if
partial_sort_copy
uninitialized_copy
但是copy_if却偏偏不在其中。
下边是正确但是不完美的copy_if的实现方法:
#include<iostream>#include<algorithm>#include<functional>using namespace std;template<typename InputIterator, typename OutputIterator, typename Predicate>OutputIterator copy_if(InputIterator begin, InputIterator end, OutputIterator destBegin, Predicate p){ return remove_copy_if(begin, end, destBegin, not1(p));}int main(){ return 0;}
注意:使用not1的原因是STL不允许“复制所有是的判别式为真的元素”,但是他允许“复制所有判别式不为真的元素”。
为了调用上边的copy_if,你传入的不仅是一个函数对象,而且应该是一个可接配的函数对象。虽然这很容易做到,但是要想成为STL算法,他不应该给客户这样的负担。标准的STL从不要求他的含函数子必须可配接,所以copy_if也应该不例外。下边的是完美的copy_if的实现:
#include<iostream>#include<algorithm>#include<functional>using namespace std;//下边是copy_if的正确实现方法template<typename InputIterator,typename OutputIterator,typename Predicate>OutputIterator copy_if(InputIterator begin, InputIterator end, OutputIterator destBegin, Predicate p){ while (begin != end) { if (p(*begin)) { *destBegin++ = *begin; ++begin; } } return destBegin;}int main(){ return 0;}
其实copy_if是很有用的,可以把这个算法加入到STL的库中,然后在适当的地方使用这个算法。
0 0
- effective stl 第36条:理解copy_if的正确实现
- copy_if的正确实现
- effective stl 第48条:总是包含(#include)正确的头文件
- copy_if函数(effective STL学习笔记)
- effective stl 第11条 :理解自定义分配子的合理用法
- effective stl 第19条:理解相等(equality)和等价(equivalence)的区别
- effective stl 第41条:理解ptr_fun/mem_fun/mem_fun_ref的由来
- Effective stl 第6条
- effective stl 第15条
- effective stl 第45条:正确区分count/find/binary_search/lower_bound/upper_bound/equal_range
- effective stl 第47条:避免产生“直写型”的代码
- Effective stl 第一章 第7、8条
- Effective STL 第一章 第9条
- Effective stl 第一章 第10条
- Effective STL 第2、3、4条
- effective stl 第35条:通过mismatch和lexicographical_compare实现简单的忽略大小写的字符串比较
- Effective STL 第12条:切勿对STL容器的线程安全性有不切实际的依赖
- effective stl 第12条: 切勿对STL容器的线程安全性有不切实际的依赖
- hrbust 1679 跑步【最小生成树相关】
- Log4j、Log4j 2、Logback、SFL4J、JUL、JCL的比较
- activity fragment viewpager的总结
- Problem C: 星球联盟(并查集+lca)
- [转]Uboot对Ext4文件系统的支持
- effective stl 第36条:理解copy_if的正确实现
- icpc大连栈
- python pil安装
- 1096. Consecutive Factors
- 排列组合问题初步
- NOIP历年搜索整理
- LeetCode 32. Longest Valid Parentheses(hard)
- 多态,抽象类,接口,UML图
- 为button添加href