注册 登录
LUPA开源社区 返回首页

fandaozhang的个人空间 http://www.lupaworld.com/?381944 [收藏] [复制] [分享] [RSS]

我的博客

迭代器 使用示例

已有 1805 次阅读2011-6-13 11:05 |系统分类:IT技术|

Use Cases

使用示例

If you use the standard containers, then you are probably using iterators in one of a few use cases.

如果你用标准容器,那么你需要使用迭代器了。

 

 

 

First of all, there is the simple task of iterating through elements, as I showed in the examples above.

首先,简单的任务:遍历元素,就像我上面给的例子那样。

 

You will probably also want to use the standard algorithms with iterators, such as copy:

你或许还会通过迭代器使用泛型算法,比如:copy()

 

list<string> x;

x.push_back("peach");

x.push_back("apple");

x.push_back("banana");

 

// Make y the same size as x.  This creates

// empty strings in y's elements.

list<string> y(x.size());

 

// This is std::copy...

copy(x.begin(), x.end(), y.begin());

 

Or, you may want nest calls to standard algorithms.The following line copies elements from x to y starting at the element "apple," if it is found:

或者,你可以迭代的使用泛型算法,比如下面的例子:

 

copy(find(x.begin(), x.end(), "apple"), x.end(), y.begin());

 

find returns an iterator that refers to the first element it finds that is equal to its argument. If no element is found, it returns its second argument, which is one past the end of the range.

Find 返回一个指向查找的第一个元素的迭代器。如果这个元素不存在,find就返回第二个参数,也就是区间的结尾。

 

You can also use the for_each algorithm to call a function for each element in the range:

你也可以使用for_each算法为在区间里的每个元素调用一个函数。

 

template<typename T>

void print(const T& val) {

   cout << val << endl;

}

// ...

for_each(y.begin(), y.end(), print<string>);

 

 

for_each works with a function like my print function above, or with a function object. Each of these algorithms will work on any of the standard containers, because the algorithms use ranges of iterators and therefore make no assumptions about the type of container.

for_each的工作原理是:使用了一个和我写的print函数相似的方式,或者是一个函数对象。这些算法将在标准容器上工作,因为算法使用的是迭代器区间,并且不管是什么类型的容器。

 

 已同步至 fandaozhang的微博

评论 (0 个评论)

facelist

您需要登录后才可以评论 登录 | 注册
验证问答 换一个 验证码 换一个

关于LUPA|人才芯片工程|人才招聘|LUPA认证|LUPA教育|LUPA开源社区 ( 浙B2-20090187 浙公网安备 33010602006705号   

返回顶部