C++ 为什么使用 string::iterator 而不是 index?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1995109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:47:50  来源:igfitidea点击:

Why use string::iterator rather than index?

c++stringiterator

提问by Jichao

Possible Duplicate:
Why use iterators instead of array indices?

可能的重复:
为什么使用迭代器而不是数组索引?

string::iterator it;
for (it = str.begin(); it < str.end(); it++) 
    cout << *it;
cout << endl;

Why not:

为什么不:

for (int i = 0; i < str.size(); i++)
    cout << str[i];
cout << endl;

It seems that string::iterator does not provide range check either. Why should we use string::iteratorrather than index?

似乎 string::iterator 也不提供范围检查。为什么要使用string::iterator而不是索引?

Thanks.

谢谢。

采纳答案by Niels Castle

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.

迭代器提供了一种统一的方式来访问任何集合/数据结构。重构代码时的灵活性是巨大的。

回答by Alon

Iterators are a standard interface. By using iterators, you can use the same algorithms with different containers. The final decision whether to use them or not is up to you based on usability and readability.

迭代器是一个标准接口。通过使用迭代器,您可以对不同的容器使用相同的算法。是否使用它们的最终决定取决于您的可用性和可读性。

For example, using the standard transform algorithm to covert std::stringto uppercase:

例如,使用标准变换算法转换std::string为大写:

std::string str = "A String";
std::transform(str.begin(), str.end(), str.begin(), ::toupper);

will result in strbeing equal to "A STRING".

将导致str等于"A STRING"

回答by lalitm

For std::string specifically, i would suggest you use indexes since it supports Random Access and its simpler that way. The only reason its "recommended" to use iterators is because iterators offer a standard interface to access sequences so that if your sequence changed to std::list for example, your iteration code would remain un-affected

特别是对于 std::string,我建议您使用索引,因为它支持随机访问并且它更简单。它“推荐”使用迭代器的唯一原因是因为迭代器提供了一个标准接口来访问序列,例如,如果您的序列更改为 std::list,您的迭代代码将保持不受影响

回答by Kornel Kisielewicz

Duplicate of:

重复:

  1. Iterators.. why use them?
  2. Why use iterators instead of array indices?
  1. 迭代器.. 为什么要使用它们?
  2. 为什么使用迭代器而不是数组索引?

That said, it's a matter of genericity. You can do a lotmore with iterators using STL than with array access. Also, if you need to refactor code, and change the string to a vector, list or rope, you wont have to rewrite your code at all.

也就是说,这是一个通用性问题。你可以做很多更使用STL比数组访问迭代器。此外,如果您需要重构代码,并将字符串更改为向量、列表或绳索,则根本不必重写代码。

Finally there's the question of safety in iteration. If you want to access the NEXT character inyour loop, with iterators you could do that safely, but increasing the array subscript might segfault on you on the last element, hence needing another check.

最后是迭代中的安全问题。如果您要访问的下一个字符你的循环,迭代器你可以做到这一点安全,但越来越多的数组下标可能会在你段错误的最后一个元素上,因此需要另一项检查。

回答by Drakosha

As stated in this question, size() method is not guaranteed to be O(1)

本问题所述,size() 方法不保证为 O(1)

回答by sepp2k

In cases where you don't know which class you're iterating over (because it's a template argument), you should use an iterator because not every class that provides an iterator also provides [](and not every class that does provide [], provides one which works in O(1) time). So by using iterator you'll make sure that the function will work with as many classes as possible (though not with C arrays).

如果您不知道要迭代哪个类(因为它是模板参数),则应该使用迭代器,因为并非每个提供迭代器的类都提供迭代器[](也不是每个确实提供的类都提供[]了一个在 O(1) 时间内工作)。因此,通过使用迭代器,您将确保该函数可以使用尽可能多的类(尽管不适用于 C 数组)。

In this specific case, I see no reason to prefer one over the other except personal preference or maybe premature optimization.

在这种特定情况下,除了个人偏好或过早优化之外,我认为没有理由偏爱其中一种。

回答by Gregory Pakosz

Both works.

两者都有效。

The main reason would be consistency: you're iterating over a collection or the characters of a string the same way, by requesting an iterator and making it advance.

主要原因是一致性:通过请求迭代器并使其前进,您正在以相同的方式迭代集合或字符串的字符。

I would not say the implementation details of ++itresulting in a pointer increment compared to str[i]involving pointer arithmetics is worth mentioning. And range checking are implementation detail as well.

++itstr[i]涉及指针算术相比,我不会说导致指针增量的实现细节值得一提。范围检查也是实现细节。

回答by Prasoon Saurav

Iterators are safer and provide more flexibility as posted by someone else too.In additon an index only can be used for containers that (efficiently) support random access(i.e. direct access to an element at a given position).An iterator is a more general concept. Iterators offer efficient traversal of linked lists, files, and a number of other data structures. It often leads to the generation of more efficientcode.

迭代器更安全,并提供更多的灵活性,正如其他人发布的那样。此外,索引只能用于(有效)支持随机访问(即直接访问给定位置的元素)的容器。迭代器是更通用的概念。迭代器提供对链表、文件和许多其他数据结构的高效遍历。它通常会导致生成更高效的代码。

回答by alemjerus

In C++, you can do many things in many different ways. This is one more example. In this case, there is no difference which method to use. But in general, iterators are faster, safer and provide more flexibility amond different types of containers.

在 C++ 中,您可以用许多不同的方式做许多事情。这又是一个例子。在这种情况下,使用哪种方法没有区别。但总的来说,迭代器更快、更安全并且在不同类型的容器中提供更大的灵活性。