Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>std::vector</code> is a template class that encapsulate a dynamic array<sup>1</sup>, stored in the heap, that grows and shrinks automatically if elements are added or removed. It provides all the hooks (<code>begin()</code>, <code>end()</code>, iterators, etc) that make it work fine with the rest of the STL. It also has several useful methods that let you perform operations that on a normal array would be cumbersome, like e.g. inserting elements in the middle of a vector (it handles all the work of moving the following elements behind the scenes).</p> <p>Since it stores the elements in memory allocated on the heap, it has some overhead in respect to static arrays.</p> <p><code>std::array</code> is a template class that encapsulate a statically-sized array, stored inside the object itself, which means that, if you instantiate the class on the stack, the array itself will be on the stack. Its size has to be known at compile time (it's passed as a template parameter), and it cannot grow or shrink.</p> <p>It's more limited than <code>std::vector</code>, but it's often more efficient, especially for small sizes, because in practice it's mostly a lightweight wrapper around a C-style array. However, it's more secure, since the implicit conversion to pointer is disabled, and it provides much of the STL-related functionality of <code>std::vector</code> and of the other containers, so you can use it easily with STL algorithms &amp; co. Anyhow, for the very limitation of fixed size it's much less flexible than <code>std::vector</code>.</p> <p>For an introduction to <code>std::array</code>, have a look at <a href="http://www.devx.com/cplus/Article/42114/0/page/" rel="noreferrer">this article</a>; for a quick introduction to <code>std::vector</code> and to the the operations that are possible on it, you may want to look at its <a href="http://en.cppreference.com/w/cpp/container/vector" rel="noreferrer">documentation</a>.</p> <hr /> <ol> <li><s>Actually, I think that in the standard they are described in terms of maximum complexity of the different operations (e.g. random access in constant time, iteration over all the elements in linear time, add and removal of elements at the end in constant amortized time, etc), but AFAIK there's no other method of fulfilling such requirements other than using a dynamic array.</s> As stated by @Lucretiel, the standard actually requires that the elements are stored contiguously, so <em>it is</em> a dynamic array, stored where the associated allocator puts it.</li> </ol>
 

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