Note that there are some explanatory texts on larger screens.

plurals
  1. POOptimal way to fill std::vector<char> buffer
    primarykey
    data
    text
    <p>This buffer should contain slots (three in this example) of equal length ( 20 in this example) <br> The buffer has to have contiguous memory so that it can be passed to a C function in non-const fashion.</p> <pre><code>const int slot_size = 20; std::vector&lt;char&gt; vbuffer; </code></pre> <p>This function takes a string, copies to a temporary buffer of the required size then appeds it to <code>vbuffer</code><br></p> <pre><code>void prepBuffer( const std::string&amp; s) { std::vector&lt;char&gt; temp(slot_size); std::copy(s.c_str(), s.c_str() + s.length() + 1, temp.begin()); vbuffer.insert(vbuffer.end(), temp.begin(), temp.end()); } </code></pre> <p>Testing the function<br></p> <pre><code>int main() { vbuffer.reserve(60); prepBuffer( "Argentina"); prepBuffer( "Herzegovina"); prepBuffer( "Zambia"); cout &lt;&lt; &amp;vbuffer[0] &lt;&lt; endl; cout &lt;&lt; &amp;vbuffer[20] &lt;&lt; endl; cout &lt;&lt; &amp;vbuffer[40] &lt;&lt; endl; } </code></pre> <p><strong>Question.</strong> There is a lot of string copying in my <code>prepBuffer</code> function. I am looking for a better way to fill up <code>vbuffer</code> with minimal copying<br> EDIT<br> The size of slots is determined elsewhere in the program. But it is not known at compile time. <br><br> <strong>EDIT</strong><br><br> In line with my accepted answer below, I have settled on this version<br></p> <pre><code>void prepBuffer(const std::string&amp; s) { assert(s.size() &lt; slot_size ); vbuffer.insert(vbuffer.end(), s.begin(), s.end()); vbuffer.insert(vbuffer.end(), slot_size - s.size(), '\0' ); } </code></pre> <p><br> Suggestions are still welcome</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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