Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there an equivalent of vector::reserve() for an std::list?
    text
    copied!<p>I have a class that looks like this:</p> <pre><code>typedef std::list&lt;char*&gt; PtrList; class Foo { public: void DoStuff(); private: PtrList m_list; PtrList::iterator m_it; }; </code></pre> <p>The function <code>DoStuff()</code> basically adds elements to <code>m_list</code> or erases elements from it, finds an iterator to some special element in it and stores it in <code>m_it</code>. It is important to note that each value of <code>m_it</code> is used in every following call of <code>DoStuff()</code>.</p> <p><strong>So what's the problem?</strong> Everything works, except that profiling shows that the operator <code>new</code> is invoked too much due to <code>list::push_back()</code> called from <code>DoStuff()</code>.</p> <p>To increase performance I want to preallocate memory for <code>m_list</code> in the initialization of <code>Foo</code> as I would do if it were an <code>std::vector</code>. The problem is that this would introduce new problems such as:</p> <ol> <li>Less efficient <code>insert</code> and <code>erase</code> of elements.</li> <li><code>m_it</code> becomes invalid as soon as the vector is changed from one call to <code>DoStuff()</code> to the next. <strong>EDIT:</strong> Alan Stokes suggested to use an index instead of an iterator, solving this issue.</li> </ol> <p><strong>My solution:</strong> the simplest solution I could think of is to implement a pool of objects that also has a linked-list functionality. This way I get a linked list <em>and</em> can preallocate memory for it.</p> <p>Am I missing something or is it really the simplest solution? I'd rather not "re-invent the wheel", and use a standard solution instead, if it exists.</p> <p>Any thoughts, workarounds or enlightening comments would be appreciated!</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