Re: Reverse a String
arnuld wrote:
On Fri, 05 Oct 2007 07:49:47 -0600, Jerry Coffin wrote:
The two iterators specifying the input to reverse_copy are required to
be bidirectional iterators, and an istream_iterator isn't a
bidirectional iterator. In C++ 0x, when we get concepts, it'll be
possible to encode requirements like this directly, to allow a much more
informative error message (interestingly, as I understand things, this
problem with error messages was one of the original motivations for the
work that resulted in the concepts proposal).
got that :-)
In any case, it wouldn't really do any good if it did work. You could
(for example) use reverse_copy in place of the _second_ copy quite
easily (vector iterators are random-access iterators, which are a
superset of bidirectional iterators) but it would just copy the strings
in reverse order, leaving each individual string unaffected.
yes, I knew that and that is why I did not even try to write that one.
I'd carry out the operation in three steps: read in the strings, then
reverse them, then write them out. You've got the reading and writing
done. The obvious way to reverse them (at least to me) would be a
functor that produces a reversed copy of an individual string, and
std::transform to apply that to the whole vector.
I have created a function that does that thing and it works :
/* a function to reverse the string */
void rev_str( std::string& in_str )
string& rev_str
{
std::string out_str;
for( std::string::const_reverse_iterator iter = in_str.rbegin();
iter != in_str.rend(); ++iter)
{
out_str.push_back( *iter );
}
in_str = out_str;
std::reverse(in_str.begin(), in_str,end()); // do all the work
return in_str;
}
then I added this for reversing each string:
std::transform( svec.begin(), svec.end(), svec.begin(), rev_str )
put the return of rev_str to
svec
actually, transform here is not a good idea, as it do call operator=,
though it do check on "this != &rhs".
you can simply write:
for (std::vector<std::string>::iterator iter = svec.begin();
iter != svec.end(); ++iter)
{
std::reverse(iter->begin(), iter->end());
}
and it raised a new mysterious error. 3rd argument to std::transform is
again svec.begin(), as I just want to put the result back into the same
vector and 4th argument is the function. I have tested the function and it
reverses a single string without any problem at all.
-- arnuld
http://lispmachine.wordpress.com