STL的算法举例

1.for_each();定义如下

template<typename InputIterator, typename Function>

Function for_each(InputIterator beg, InputIterator end, Function f) {
  while(beg != end) 
    f(*beg++);

}

demo:

void print(int elem)
{
cout << elem << ' ';
}
int main()
{
vector<int> coll;

for(int i = 48; i <= 58; ++i)
{
coll.push_back(i);
}

for_each(coll.begin(), coll.end(), print);
cout << endl;
system("pause");
return 0;
}

2.copy()函数定义

template<class InputIterator, class OutputIterator>
   OutputIterator copy(
      InputIterator _First, 
      InputIterator _Last, 
      OutputIterator _DestBeg
   );

demo:

int main()
{
typedef vector<int>                 int_vector;
typedef istream_iterator<int> istream_itr;
typedef ostream_iterator<int> ostream_itr;
typedef back_insert_iterator< int_vector > back_ins_itr;

int src[]= {1, 2, 3, 4, 5, 6, 7};
        int_vector srcVec(7, 0); 
        ofstream otext("F:\\test.txt");//定义文件输出流

       copy (src, src + 7, srcVec.begin());      //从容器copy到容器
       copy(srcVec.begin(), srcVec.end(), ostream_itr(cout," "));//从容器copy到标准输出流

copy(istream_itr(cin), istream_itr(), back_ins_itr(srcVec));//将标准输入流copy到容器
copy(srcVec.begin(), srcVec.end(), ostream_itr(otext," "));//从容器copy到文件输出流

copy(istream_itr(cin), istream_itr(), ostream_itr(cout," "));//将标准输入流copy到标准输出流
copy(istream_itr(cin), istream_itr(), ostream_itr(otext," "));//将标准输入流copy到文件输出流

        cout << endl;
system("pause");
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值