Re: Andrei's "iterators must go" presentation
Hakusa wrote:
Sorry, this is in reply to no particular one, but...
I hacked out a function earlier today and, thinking of this thread,
wanted to see how it would look with ranges. But, either due to my
misunderstanding with ranges, or the nature of ranges, or my problem,
the range version can't do what the random access iterator version
can.
Here's the code for the iterator version (one of).
// Split container 'what' by 'that'.
// ex: split( string("two words"), ' ' ) ==> { string("two"), string
("words") }
template< typename C, typename T > static
std::vector<C> split_disp( const C& what, const T& that,
std::random_access_iterator_tag )
{
typedef typename C::const_iterator CIt;
std::vector<C> ret;
CIt from = what.begin(), end = what.end();
while( from < end )
{
CIt to = std::find( from, end, that );
ret.push_back( C(from,to) );
from = ++to; // ++to to skip the 'that' to should be pointing
to.
}
return ret;
}
Your code is ill-formed.
while (from < end) {
CIt to = std::find(from, end, that);
ret.push_back( C(from, to) );
// The next line says:
// If we have found a separator, advance one element,
// otherwise we have reached the end and we're done.
from = to != end ? ++to : to;
}
Someone else would prefer:
if (to != end) ++to;
from = to;
Now you can do the same with ranges.
Also, please note that "past-the-end iterator" _is_ 'end'.
Taken from the Standard:
"Just as a regular pointer to an array guarantees that there is
a pointer value pointing past the last element of the array, so for
any iterator type there is an iterator value that points past
the last element of a corresponding sequence. These values are called
past-the-end values."
So, instead of past-the-end iterator, you will have an empty range.
--
Dragan
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]