首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

TCPL - C++迭代器的用法 - 操作数组跟数据流

2013-11-08 
TCPL - C++迭代器的用法 - 操作数组和数据流C的迭代器(iterator)是个非常好的技术,能灵活运用内带来很优雅

TCPL - C++迭代器的用法 - 操作数组和数据流

C++的迭代器(iterator)是个非常好的技术,能灵活运用内带来很优雅的程序代码。

 1 遍历数组

最简单的也是最常用的就是遍历访问一个数组了,如检查一个字符串里面是否含有某个字符:

bool has_c(const string& s, char c) // does s contain the character c?{auto p = find(s.begin(),s.end(),c);if (p!=s.end())return true;elsereturn false;}

C++的数组访问习惯就是,到了end()就代表遍历结束。其中end位置是代表最后一个元素的下个位置。

当然程序可以进一步简化:

bool has_c(const string& s, char c) // does s contain the character c?{return find(s.begin(),s.end(),c)!=s.end();}

2 下面是一个使用模板查找某数组某个元素,然后替换的测试程序:
#include<iostream>#include<vector>#include<string>#include<list>using namespace std;template<typename C, typename V>vector<typename C::iterator>find_all(C& c,V v){//Caution!:: You just have to add every typename befor C,//if the C need to use :://The typename is needed to inform the compiler that C’s iterator is supposed to be a type and not a value of some type, say, the integer 7.vector<typename C::iterator>res;for(auto p=c.begin();p!=c.end();++p)if(*p==v)res.push_back(p);return res;}void test(){string m=("Mary hod o little lomb");cout<<m<<endl;for(auto p:find_all(m,'o'))*p = 'a';cout<<m<<endl;double dou[] = {1.1,2.2,3.3,4.5,2.3,2.2};list<double> ld(dou,dou+6);for(auto x:ld)cout<<x<<" ";cout<<endl;for(auto p:find_all(ld,2.2))*p = 100.0;for(auto x:ld)cout<<x<<" ";cout<<endl;}int main(){test();return 0;}

3 C++迭代器的用法都很通用,有指针和下标的通用特征,高级的用法是用在数据流中去.

如下把string写到cout中去,其实就是把字符输出到屏幕上:

 

ostream_iterator<string> oo {cout}; 
int main(){?oo = "Hello, "; //就是cout<<"Hello, "++oo;?oo = "world!\n"; //就是cout<<"wor ld!\n"}


对上面的oo赋值就相当于赋值给cout,也就是可以在屏幕上显示出来。

同样道理可以操作输入流:

istream_iterator<string> ii {cin};

有点不同的就是我们可以指定其输入的结束符,列如下面就是其默认的结束符,一般txt文本中都有自动带上这样的结束符的。

istream_iterator<string> eos {};

 

总结:

对比一般用下标的编程法,就会觉得用迭代器会大大减少下标出错的几率。

Reference:

The C++ Programming Language 4ed

 

热点排行