Iterating std::string elements
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];
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);
Why on earth would you use the top code instead of str.end() - 1?
Edit: Or str.back(), which is far more container-generic.
精彩评论