Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Using the <code>std::vector&lt;T&gt;</code> class:</p> <ul> <li><p>...is <em>just as fast</em> as using built-in arrays, assuming you are doing only the things built-in arrays allow you to do (read and write to existing elements).</p></li> <li><p>...automatically resizes when new elements are inserted.</p></li> <li><p>...allows you to insert new elements <em>at the beginning</em> or <em>in the middle</em> of the vector, automatically "shifting" the rest of the elements "up"( does that make sense?). It allows you to remove elements anywhere in the <code>std::vector</code>, too, automatically shifting the rest of the elements down.</p></li> <li><p>...allows you to perform a range-checked read with the <code>at()</code> method (you can always use the indexers <code>[]</code> if you don't want this check to be performed).</p></li> </ul> <p>There are <strike>two</strike> three main caveats to using <code>std::vector&lt;T&gt;</code>:</p> <ol> <li><p>You don't have reliable access to the underlying pointer, which <em>may</em> be an issue if you are dealing with third-party functions that demand the address of an array.</p></li> <li><p>The <code>std::vector&lt;bool&gt;</code> class is silly. It's implemented as a condensed bitfield, not as an array. Avoid it if you want an array of <code>bool</code>s!</p></li> <li><p>During usage, <code>std::vector&lt;T&gt;</code>s are going to be a bit larger than a C++ array with the same number of elements. This is because they need to keep track of a small amount of other information, such as their current size, and because whenever <code>std::vector&lt;T&gt;</code>s resize, they reserve more space then they need. This is to prevent them from having to resize every time a new element is inserted. This behavior can be changed by providing a custom <code>allocator</code>, but I never felt the need to do that!</p></li> </ol> <hr> <p>Edit: After reading Zud's reply to the question, I felt I should add this:</p> <p>The <code>std::array&lt;T&gt;</code> class is not the same as a C++ array. <code>std::array&lt;T&gt;</code> is a very thin wrapper around C++ arrays, with the primary purpose of hiding the pointer from the user of the class (in C++, arrays are implicitly cast as pointers, often to dismaying effect). The <code>std::array&lt;T&gt;</code> class also stores its size (length), which can be very useful.</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