Chinaunix首页 | 论坛 | 博客
  • 博客访问: 496321
  • 博文数量: 111
  • 博客积分: 3160
  • 博客等级: 中校
  • 技术积分: 1982
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-24 11:49
个人简介

低调、勤奋。

文章分类

全部博文(111)

文章存档

2014年(2)

2013年(26)

2012年(38)

2011年(18)

2010年(27)

分类: C/C++

2013-01-09 22:10:42

一、插入迭代器
C++语言提供了三种插入器,其差别在于插入元素的位置不同。

back_inserter, 创建使用push_back实现插入的迭代器。
front_inerter,创建使用push_front实现插入
inserter,使用insert实现插入操作

二、反向迭代器

反向迭代器是一种反向遍历容器的迭代器。也就是,从最后一个元素到第一个元素遍历容器。反向迭代器将自增(和自减)的含义反过来了:对于反向迭代器,++ 运算将访问前一个元素,而 -- 运算则访问下一个元素。


// reverse iterator of vector from back to front 

 vector::reverse_iterator r_iter; 

 for (r_iter = vec.rbegin(); r_iter != vec.rend(); ++r_iter) // decrements iterator one element 

 cout << *r_iter << endl; // prints 9,8,7,...0


//单词列表FIRST,MIDDLE,LAST

如果要输出列表中最后一个单词,可使用反向迭代器:

// find last element in a comma-separated list 
string::reverse_iterator rcomma = find(line.rbegin(), line.rend(), ',');
// wrong: will generate the word in reverse order 
 cout << string(line.rbegin(), rcomma) << endl;

则将输出 TSAL!


使用反向迭代器时,以逆序从后向前处理 string 对象。为了得到正确的输出,必须将反向迭代器 line.rbegin() 和 rcomma 转换为从前向后移动的普通迭代器。其实没必要转换 line.rbegin(),因为我们知道转换的结果必定是 line.end()。只需调用所有反向迭代器类型都提供的成员函数 base 转换 rcomma 即可:

// ok: get a forward iterator and read to end of line 

 cout << string(rcomma.base(), line.end()) << endl;


三、const 迭代器

定义为const_iterator 类型。这样做是因为我们不希望使用这个迭代器来修改容器中的元素。


Table 11.3. Iterator Categories 表 11.3. 迭代器种类

Input iterator(输入迭代器)

Read, but not write; increment only

读,不能写;只支持自增运算

Output iterator(输出迭代器)

Write, but not read; increment only

写,不能读;只支持自增运算

Forward iterator(前向迭代器)

Read and write; increment only

读和写;只支持自增运算

Bidirectional iterator(双向迭代器)

Read and write; increment and decrement

读和写;支持自增和自减运算

Random access iterator(随机访问迭代器)

Read and write; full iterator arithmetic

读和写;支持完整的迭代器算术运算

阅读(1449) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~