为什么使用string :: iterator而不是index? [英] Why use string::iterator rather than index?
本文介绍了为什么使用string :: iterator而不是index?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
为什么使用迭代器而不是数组索引?
string::iterator it;
for (it = str.begin(); it < str.end(); it++)
cout << *it;
cout << endl;
为什么不:
for (int i = 0; i < str.size(); i++)
cout << str[i];
cout << endl;
似乎string :: iterator也不提供范围检查。我们为什么要使用 string :: iterator
而不是索引?
It seems that string::iterator does not provide range check either. Why should we use string::iterator
rather than index?
谢谢。
推荐答案
索引只能用于支持随机访问的容器 - 直接访问给定位置。
The index can only be used for containers that support random access - direct access to a given position.
迭代器提供了一种访问任何集合/数据结构的统一方法。重构代码时的灵活性是巨大的。
The iterator offers a unified way to access any collection/data structure. The flexibility when refactoring your code is immense.
这篇关于为什么使用string :: iterator而不是index?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文