views:

309

answers:

2

Hi,

Given just a std::string iterator, is it possible to determine the start and end points of the string? Supposing that I don't have access to the string object and so cannot call string.begin() and string.end(), and all I can do is increment or decrement the iterator and test the value.

Thanks, Phil

+10  A: 

The short answer is no. The long answer is, because iterators aren't expected to know about the containers or ranges that are iterating over, they are only expected to

  • Be able to jump to the next element (inc or dec to next or prev)
  • Dereference themselves so as to reveal a reference to the value they are pointing to
  • And over course compare themselves with other iterators most importantly an "end" iterator of some kind.

Furthermore certain types iterators may do more than just the above, but principally they are all required to have/perform the above in some form or another.

Beh Tou Cheh
Yep you definitly need iterators pointing at the end or the start to compare your current iterator, something that could be determined when you define the string?
Apoc
A: 
  • For the end point of the string: Assume the internal character string is null-terminated. Then through dereferencing the iterator to see if they're '\0' to determine the next position is end point. But for other non null-terminated string, it's impossible to get to know such information.
  • For the start point of the string: No way to do such thing.

The default std::string::iterator is just a random, bi-direction iterator, doesn't know anything about container.

But if you're working on Visual C++ platform, maybe you can use some hacking way like following to get the control to its container, but it's very dangerous:

  // it is the passed in string::iterator parameter.
  if (it._Has_container()) {
      string* strRef = (string*)it._Mycont;
  }
meta