本文共 1821 字,大约阅读时间需要 6 分钟。
学习资料:
在STL中有众多的algorithm,碰到了就复习一下
copy
templateOutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);
在template我们需要注意到两个地方,一个是它的copy是可以通过iterator迭代copy的,而输出也是Iterator
看看官网的介绍
The behavior of this function template is equivalent to:
templateOutputIterator copy (InputIterator first, InputIterator last, OutputIterator result){ while (first!=last) { *result = *first; ++result; ++first; } return result;}
它的作用很清晰了,我今天看到一个特别的用法,有个iterator的用法很特别,叫做ostream_iterator
我们看看先看看ostream_iterator的定义:
template> class ostream_iterator;
这里的T就是element的type,charT表示stream handles,例如cout,traits表示的是元素之间的间隔,它的作用是将元素放入output stream.
看看官方的example
// ostream_iterator example#include// std::cout#include // std::ostream_iterator#include // std::vector#include // std::copyint main () { std::vector myvector; for (int i=1; i<10; ++i) myvector.push_back(i*10); std::ostream_iterator out_it (std::cout,", "); std::copy ( myvector.begin(), myvector.end(), out_it ); return 0;}
Possible output:
10, 20, 30, 40, 50, 60, 70, 80, 90,
再来看看set_intersection
作用:寻找两个sorted ranges的交集,注意一定是经过排序的range,否则会存在错误
templateOutputIterator set_intersection (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result){ while (first1!=last1 && first2!=last2) { if (*first1<*first2) ++first1; else if (*first2<*first1) ++first2; else { *result = *first1; ++result; ++first1; ++first2; } } return result;}
在这里可以看出来,必须是排序的range才能找到正确的答案
相似的函数还有set_union,set_difference,set_symmetric_difference,merge
转载地址:https://blog.csdn.net/zhouzhouasishuijiao/article/details/88051768 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!