设为首页 加入收藏

TOP

标准模板库(STL)List介绍(四)
2011-06-07 12:31:23 】 浏览:13597
Tags:标准 模板 STL List 介绍
 
  
用STL的通用算法for_each来处理list中的元素 
     使用STL list和 iterator,我们要初始化、比较和给iterator增量来遍历这个容器。STL通用的for_each 算法能够减轻我们的工作。  
  
  /* 
|| How to print a simple STL list MkII 
*/ 
#include <iostream.h> 
#include <string> 
#include <list> 
#include <algorithm> 
  
PrintIt (string& StringToPrint) { 
   cout << StringToPrint << endl; 
  
int main (void) { 
   list<string> FruitAndVegetables; 
   FruitAndVegetables.push_back("carrot"); 
   FruitAndVegetables.push_back("pumpkin"); 
   FruitAndVegetables.push_back("potato"); 
   FruitAndVegetables.push_front("apple"); 
   FruitAndVegetables.push_front("pineapple"); 
   
   for_each  (FruitAndVegetables.begin(), FruitAndVegetables.end(), PrintIt); 
     在这个程序中我们使用STL的通用算法for_each()来遍历一个iterator的范围,然后调用PrintIt()来处理每个对象。 我们不需要初始化、比较和给iterator增量。for_each()为我们漂亮的完成了这些工作。我们执行于对象上的 操作被很好的打包在这个函数以外了,我们不用再做那样的循环了,我们的代码更加清晰了。  
  
     for_each算法引用了iterator范围的概念,这是一个由起始iterator和一个末尾iterator指出的范围。 起始iterator指出操作由哪里开始,末尾iterator指明到哪结束,但是它不包括在这个范围内。  
  
  
首页 上一页 1 2 3 4 5 6 7 下一页 尾页 4/18/18
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇 C++语言的url encode 和decode 下一篇C++ map的基本操作和使用

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目