Francesco S. Carta <>, on 05/09/2010 20:04:18, wrote:
> Marc <>, on 05/09/2010 10:54:46, wrote:
>
>> On 5 sep, 19:27, "Francesco S. Carta"<entul...@gmail.com> wrote:
>>> SG<s.gesem...@gmail.com>, on 05/09/2010 10:17:37, wrote:
>>>> On 5 Sep., 19:05, "Francesco S. Carta" wrote:
>>>>> in place, yes: use the
>>>>> std::string::insert() method.
>>>
>>>> Or better yet, resize() to final size, assign the non-null characters
>>>> in a backwards loop and set a couple of chars to zero:
>>>
>>>> void sillify(string& io)
>>>> {
>>>> size_t len1 = io.size();
>>>> io.resize(len1*2,'\0');
>>>> for (size_t k=len1; k-->1
>>>> io[k*2] = io[k];
>>>> for (size_t k=1; k<len1; k+=2)
>>>> io[k] = '\0';
>>>> }
>>>
>>> Define "better".
>>>
>>> void smartify(string& s) {
>>> for(int i = 1, e = s.size()*2; i< e; i+=2) {
>>> s.insert(i, 1, '\0');
>>> }
>>> }
>>
>> Faster. SG's code has linear complexity and yours is quadratic.
>> Readability is something else...
>
> Exactly. So neither is better than the other unless we associate
> "better" to "more readable" or to "faster" 
>
Just for the records, a better solution, in my opinion, is to build an
appropriately sized new string and copying the original chars at the
appropriate positions - a compromise between readability and speed,
somewhat:
void foo(string& s) {
string r(s.size()*2, '\0');
for(int i = 0, e = s.size(); i < e; ++i) {
r[i*2] = s[i];
}
s.swap(r);
}
ASSUMING that the OP really wants exactly this - WRT Alf P. Steinbach's
notes in the other post.
--
FSC -
http://userscripts.org/scripts/show/59948
http://fscode.altervista.org -
http://sardinias.com