effective stl 第36条:理解copy_if的正确实现
2016-09-29 18:57
363 查看
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的实现方法:
注意:使用not1的原因是STL不允许“复制所有是的判别式为真的元素”,但是他允许“复制所有判别式不为真的元素”。
为了调用上边的copy_if,你传入的不仅是一个函数对象,而且应该是一个可接配的函数对象。虽然这很容易做到,但是要想成为STL算法,他不应该给客户这样的负担。标准的STL从不要求他的含函数子必须可配接,所以copy_if也应该不例外。下边的是完美的copy_if的实现:
其实copy_if是很有用的,可以把这个算法加入到STL的库中,然后在适当的地方使用这个算法。
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的库中,然后在适当的地方使用这个算法。
相关文章推荐
- effective stl 第28条:正确理解由reverse_iterator的base()成员函数所长生的iterator的用法
- if __name__ == '__main__' 如何正确理解?(转)
- 正确理解RESET类型的INPUT控件实现重置效果的机制
- python中 if __name__ == '__main__' 如何正确理解?
- if __name__ == '__main__' 如何正确理解?
- if __name__ == '__main__' 如何正确理解?
- 理解 shared_ptr实现copy-on-write(COW)
- 理解 shared_ptr实现copy-on-write(COW)
- 【Python】Python 中if (__name__ == '__main__') 如何正确理解?
- [Android App]IFCTT,即:If Copy Then That,一个基于IFTTT的"This"实现
- if __name__ == '__main__' 如何正确理解?
- Python:Python中if __name__ == '__main__' 如何正确理解?
- 正确理解RESET类型的INPUT控件实现重置效果的机制
- if __name__ == '__main__' 如何正确理解?
- python中 if __name__ == '__main__' 如何正确理解?
- if __name__ == '__main__' 如何正确理解?
- 条款11:理解自定义分配器的正确用法
- GP随笔: IF模板的一种非偏特化实现
- 市面上所有号称"虚拟机","防火墙"的实时监控杀毒软件无一不是使用的IFSHOOK技术.但是同时也有一些朋友不断写MAIL给我打听如何实现读写的监控.下面给出用VTOOLSD写的代码.也就是所有实时杀毒软件的奥秘.同时,很多拦截文件操作的软件,例如对目录加
- 正确理解Traceback的含义