Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is so easy it amazes me how many smart people have screwed it up.</p> <p><strong>C++03:</strong></p> <pre><code>std::string s; for (std::vector&lt;std::string&gt;::const_iterator i = v.begin(); i != v.end(); ++i) s += *i; return s; </code></pre> <p><strong>C++11:</strong> (the MSVC2010 subset)</p> <pre><code>std::string s; std::for_each(v.begin(), v.end(), [&amp;](const std::string &amp;piece){ s += piece; }); return s; </code></pre> <p><strong>C++11:</strong></p> <pre><code>std::string s; for (const auto &amp;piece : v) s += piece; return s; </code></pre> <p><strong>Don't use <code>std::accumulate</code> for string concatenation</strong>, it is a classic <a href="http://en.wikipedia.org/wiki/Schlemiel_the_Painter%27s_algorithm">Schlemiel the Painter's algorithm</a>, even worse than the usual example using <code>strcat</code> in C. Without C++11 move semantics, it incurs two unnecessary copies of the accumulator for each element of the vector. Even with move semantics, it still incurs one unnecessary copy of the accumulator for each element.</p> <p>The three examples above are <strong>O(n)</strong>.</p> <p><code>std::accumulate</code> is <strong>O(n^2)</strong> for strings.</p> <hr> <p>You could make <code>std::accumulate</code> O(n) for strings by supplying a custom functor:</p> <pre><code>std::string s = std::accumulate(v.begin(), v.end(), std::string{}, [](std::string &amp;s, const std::string &amp;piece) -&gt; decltype(auto) { return s += piece; }); </code></pre> <p>Note that <code>s</code> must be a reference to non-const, the lambda return type must be a reference (hence <code>decltype(auto)</code>), and the body must use <code>+=</code> not <code>+</code>.</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