标准模板库(STL)List介绍(四)

2011-06-07 12:31:23 · 作者: · 浏览: 9215
 
  
用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指明到哪结束,但是它不包括在这个范围内。