Actually, there's one small problem with his solution: std::strings allow nuls in the middle.
You're not using properly the iterator:
1 2
|
for (std::string::iterator i=str.begin(),end=str.end();i!=end;i++)
*i='x';
|
Iterators are not primitives, they're objects. Each assignment, each comparison, each increment, and each dereference performed on an iterator is a function call. A function call implies quite a few things. Pushing various things onto the stack, jumping to a completely different location, then popping the stack and jumping back. It's one thing if that's the body of your loop, and it's another if more time is spent checking if the loop is supposed to continue than performing the loop itself.
In this example, the overhead is particularly large. All the loop does is assign integers to consecutive chararacters in memory, but in order to do that with iterators, there are three function calls per loop: one to compare, one to dereference, and one to increment. This makes the loop take several times longer.
Compare that to the simple task of incrementing an integer, dereferencing it twice, and comparing an integer. A single level of dereference carries almost no penalty; only the time it takes the processor to load the variable from RAM. Incrementing an integer takes three instructions, and comparing two integers (not counting the jump) takes three instructions. The body itself takes only two instructions.