数据结构与算法复习(三) STL中的Algorithm

学习资料:http://www.cplusplus.com/reference/algorithm/copy/?kw=copy

在STL中有众多的algorithm,碰到了就复习一下

copy

template <class InputIterator, class OutputIterator> 
OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);

在template我们需要注意到两个地方,一个是它的copy是可以通过iterator迭代copy的,而输出也是Iterator

看看官网的介绍

The behavior of this function template is equivalent to:

template<class InputIterator, class OutputIterator>
  OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
  while (first!=last) {
    *result = *first;
    ++result; ++first;
  }
  return result;
}

                                                                                                                                                         

它的作用很清晰了,我今天看到一个特别的用法,有个iterator的用法很特别,叫做ostream_iterator

我们看看先看看ostream_iterator的定义:

template <class T, class charT=char, class traits=char_traits<charT> > class ostream_iterator;

这里的T就是element的type,charT表示stream handles,例如cout,traits表示的是元素之间的间隔,它的作用是将元素放入output stream.

看看官方的example

// ostream_iterator example
#include <iostream>     // std::cout
#include <iterator>     // std::ostream_iterator
#include <vector>       // std::vector
#include <algorithm>    // std::copy

int main () {
  std::vector<int> myvector;
  for (int i=1; i<10; ++i) myvector.push_back(i*10);

  std::ostream_iterator<int> 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,否则会存在错误

template <class InputIterator1, class InputIterator2, class OutputIterator>
  OutputIterator 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

                                                                                                                                    

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值