tags:

views:

70

answers:

2

does it take constant time to move the iterator to elements of string in following:

std::string str // string of size 100 MB
std::string::iterator iter = str.begin();
std::advance(iter, str.size()-1);

would it take constant time as in searching by index?

char c = str[str.size()-1];
+3  A: 

Yes, that's correct. This is guaranteed by the C++ standard (§24.3, Iterator operations):

Since only random access iterators provide + and - operators, the library provides two function templates advance and distance. These function templates use + and - for random access iterators (and are, therefore, constant time for them);

Matthew Flaschen
A: 

Why on earth would you use the top code instead of str.end() - 1?

Edit: Or str.back(), which is far more container-generic.

DeadMG
More of a comment. :)
GMan
It doesn't rely on iter being a Random Access Iterator. In the specific case this isn't important but could if it is too simplified.
pmr