Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use string::iterator rather than index? [duplicate]

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?

Thanks.

like image 486
Jichao Avatar asked Jan 03 '10 14:01

Jichao


People also ask

Are iterators faster than indexing?

Depending on the actual container, incrementing an iterator might be faster than indexing (think linked lists).

Why iterator is used instead of for loop?

Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.

What is difference between iterator and index?

An index (or key) is used to look up data in a container. The simplest case would be the integer indexes of an array, but containers like std::map can have nearly any type as an index. An iterator is a class which represents a position in a container.


3 Answers

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.

like image 50
Niels Castle Avatar answered Oct 20 '22 19:10

Niels Castle


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::string str = "A String";
std::transform(str.begin(), str.end(), str.begin(), ::toupper);

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

like image 37
Alon Avatar answered Oct 20 '22 17:10

Alon


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

like image 37
lalitm Avatar answered Oct 20 '22 17:10

lalitm