Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>#include &lt;string&gt; const char digit_pairs[201] = { "00010203040506070809" "10111213141516171819" "20212223242526272829" "30313233343536373839" "40414243444546474849" "50515253545556575859" "60616263646566676869" "70717273747576777879" "80818283848586878889" "90919293949596979899" }; std::string&amp; itostr(int n, std::string&amp; s) { if(n==0) { s="0"; return s; } int sign = -(n&lt;0); unsigned int val = (n^sign)-sign; int size; if(val&gt;=10000) { if(val&gt;=10000000) { if(val&gt;=1000000000) size=10; else if(val&gt;=100000000) size=9; else size=8; } else { if(val&gt;=1000000) size=7; else if(val&gt;=100000) size=6; else size=5; } } else { if(val&gt;=100) { if(val&gt;=1000) size=4; else size=3; } else { if(val&gt;=10) size=2; else size=1; } } size -= sign; s.resize(size); char* c = &amp;s[0]; if(sign) *c='-'; c += size-1; while(val&gt;=100) { int pos = val % 100; val /= 100; *(short*)(c-1)=*(short*)(digit_pairs+2*pos); c-=2; } while(val&gt;0) { *c--='0' + (val % 10); val /= 10; } return s; } std::string&amp; itostr(unsigned val, std::string&amp; s) { if(val==0) { s="0"; return s; } int size; if(val&gt;=10000) { if(val&gt;=10000000) { if(val&gt;=1000000000) size=10; else if(val&gt;=100000000) size=9; else size=8; } else { if(val&gt;=1000000) size=7; else if(val&gt;=100000) size=6; else size=5; } } else { if(val&gt;=100) { if(val&gt;=1000) size=4; else size=3; } else { if(val&gt;=10) size=2; else size=1; } } s.resize(size); char* c = &amp;s[size-1]; while(val&gt;=100) { int pos = val % 100; val /= 100; *(short*)(c-1)=*(short*)(digit_pairs+2*pos); c-=2; } while(val&gt;0) { *c--='0' + (val % 10); val /= 10; } return s; } </code></pre> <p>This will blow up on systems that disallow unaligned memory accesses (in which case, the first unaligned assignment via <code>*(short*)</code> would cause a segfault), but should work very nicely otherwise.</p> <p>One important thing to do is to minimize the use of <code>std::string</code>. (Ironic, I know.) In Visual Studio, for example, most calls to methods of std::string are not inlined, even if you specify /Ob2 in compiler options. So even something as trivial as a call to <code>std::string::clear()</code>, which you might expect to be very fast, can take 100 clockticks when linking CRT as a static library, and as much as 300 clockticks when linking as a DLL.</p> <p>For the same reason, returning by reference is better because it avoids an assignment, a constructor and a destructor.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload