为什么使用string::iterator而不是索引?(复制)

时间:2022-11-18 19:00:41

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::iterator rather than index?

似乎字符串::iterator也不提供范围检查。为什么我们应该使用string::iterator而不是索引?

Thanks.

谢谢。

10 个解决方案

#1


25  

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.

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

#2


16  

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::string to uppercase:

例如,使用标准变换算法将std::字符串转换为大写:

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

will result in str being equal to "A STRING".

将导致str等于“字符串”。

#3


5  

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,那么您的迭代代码将不会受到影响

#4


2  

Duplicate of:

复制:

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

That said, it's a matter of genericity. You can do a lot more 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的迭代器可以做得更多。此外,如果您需要重构代码,并将字符串更改为向量、列表或rope,那么您根本不需要重写代码。

Finally there's the question of safety in iteration. If you want to access the NEXT character in your 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.

最后一个问题是迭代的安全性。如果您想访问循环中的下一个字符,可以使用迭代器安全地访问,但是增加数组下标可能会在最后一个元素上分段错误,因此需要进行另一次检查。

#5


1  

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

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

#6


1  

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)时间内工作的类)。因此,通过使用iterator,您将确保该函数可以使用尽可能多的类(尽管不使用C数组)。

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

在这个具体的例子中,我认为除了个人偏好或者可能是过早的优化之外,没有理由选择其中之一。

#7


0  

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 ++it resulting in a pointer increment compared to str[i] involving pointer arithmetics is worth mentioning. And range checking are implementation detail as well.

与涉及指针算术的str[I]相比,+it导致指针增量的实现细节是不值得一提的。范围检查也是实现的细节。

#8


0  

I assume one further reason why iterators should be preferred over indices is that not all collections support constant-time random access.

我假设迭代器优于索引的另一个原因是并非所有集合都支持常量时间随机访问。

For example, if you want the n-th element in a linked list, you need to traverse all preceding elements (with indices 0..n-1) until you get to the n-th element. (This operation takes linear time.)

例如,如果您想要一个链表中的第n个元素,您需要遍历所有前面的元素(索引0..n-1),直到第n个元素。(这个操作需要线性时间。)

An (sequential) iterator remembers where it is in a collection and doesn't always have to start again from the beginning when you want the next element. In your example, you don't actually need to access the characters in a string in random order, but only sequentially, so using an iterator will almost certainly be faster (constant-time).

(顺序)迭代器会记住它在集合中的位置,并且在需要下一个元素时,并不总是需要从头开始。在您的示例中,实际上不需要按随机顺序访问字符串中的字符,而只需按顺序访问,因此使用迭代器几乎肯定会更快(常量时间)。

#9


0  

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 efficient code.

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

#10


-2  

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++中,你可以用很多不同的方式做很多事情。这是另一个例子。在这种情况下,使用哪种方法没有区别。但一般来说,迭代器速度更快、更安全,并且在不同类型的容器中提供了更大的灵活性。

#1


25  

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.

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

#2


16  

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::string to uppercase:

例如,使用标准变换算法将std::字符串转换为大写:

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

will result in str being equal to "A STRING".

将导致str等于“字符串”。

#3


5  

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,那么您的迭代代码将不会受到影响

#4


2  

Duplicate of:

复制:

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

That said, it's a matter of genericity. You can do a lot more 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的迭代器可以做得更多。此外,如果您需要重构代码,并将字符串更改为向量、列表或rope,那么您根本不需要重写代码。

Finally there's the question of safety in iteration. If you want to access the NEXT character in your 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.

最后一个问题是迭代的安全性。如果您想访问循环中的下一个字符,可以使用迭代器安全地访问,但是增加数组下标可能会在最后一个元素上分段错误,因此需要进行另一次检查。

#5


1  

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

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

#6


1  

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)时间内工作的类)。因此,通过使用iterator,您将确保该函数可以使用尽可能多的类(尽管不使用C数组)。

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

在这个具体的例子中,我认为除了个人偏好或者可能是过早的优化之外,没有理由选择其中之一。

#7


0  

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 ++it resulting in a pointer increment compared to str[i] involving pointer arithmetics is worth mentioning. And range checking are implementation detail as well.

与涉及指针算术的str[I]相比,+it导致指针增量的实现细节是不值得一提的。范围检查也是实现的细节。

#8


0  

I assume one further reason why iterators should be preferred over indices is that not all collections support constant-time random access.

我假设迭代器优于索引的另一个原因是并非所有集合都支持常量时间随机访问。

For example, if you want the n-th element in a linked list, you need to traverse all preceding elements (with indices 0..n-1) until you get to the n-th element. (This operation takes linear time.)

例如,如果您想要一个链表中的第n个元素,您需要遍历所有前面的元素(索引0..n-1),直到第n个元素。(这个操作需要线性时间。)

An (sequential) iterator remembers where it is in a collection and doesn't always have to start again from the beginning when you want the next element. In your example, you don't actually need to access the characters in a string in random order, but only sequentially, so using an iterator will almost certainly be faster (constant-time).

(顺序)迭代器会记住它在集合中的位置,并且在需要下一个元素时,并不总是需要从头开始。在您的示例中,实际上不需要按随机顺序访问字符串中的字符,而只需按顺序访问,因此使用迭代器几乎肯定会更快(常量时间)。

#9


0  

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 efficient code.

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

#10


-2  

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++中,你可以用很多不同的方式做很多事情。这是另一个例子。在这种情况下,使用哪种方法没有区别。但一般来说,迭代器速度更快、更安全,并且在不同类型的容器中提供了更大的灵活性。