What variations of vector-like containers already widely established? Do I have to write my own? [closed]
In my program, I often need an owning array-like container - i.e. for data stored contiguously in memory, but vector is too flexible and less practical or efficient than it could be.
The requirements differ from std::vector
in one or more aspects such as:
- Elements can only be inserted at the end, without moving other elements
- Capacity cannot be changed after construction / after compilation
- Size can't be changed after construction / after compilation
- Storage is inherent in the class and does not involve an allocator
- No weird special-casing for a single type like
std::vector<bool>
- References and/or iterators don't get invalidated on insertion
- etc.
If necessary, I'll implement such a container myself, but likely it already exists in the standard library or in a popular one like Boost.
The thing is, it can be hard to find, maybe it has a fancy name that you don't expect. So, what vector-like containers within the above parameter space exist?
Even if my requirements aren't met in an existing container, a reference list helps: if I do end up implementing a new container, I can adopt appropriate names and avoid confusing names.
Here are the ones I know of:
- Traditional a.k.a. plain a.k.a. C array
vector
-
unique_ptr
with an array-type template argument array
valarray
dynarray
-
static_vector
(see also here) small_vector
stable_vector
There are also "variable-length arrays" and "arrays with runtime bounds", which do not exist in C++; the former exists in C. See also this question and this answer about these non-C++ containers.
Let's compare the features of all of these. If the container you want doesn't match one of the lines below exactly, you'll need to implement your own and choose a name for it.
Criterion | C array | array | vector | unique_ptr | valarray | dynarray | static_vector | small_vector | stable_vector |
---|---|---|---|---|---|---|---|---|---|
Origin/library | language | std | std | std | std | discarded std | Boost | Boost | Boost |
Type parameters | T,N | T,N | T,A | T | T | T | T,C,O | T,N,A,O | T,A |
Capacity fix time | Compile | Compile | Never | (Construct) | Never | Construct | Compile | Never | Never |
Size fix time | Compile | Compile | Never | N/A | Never | Never | Construct | Never | Never |
Size = capacity always? | ✔ | ✔ | ✕ | N/A | ✕ | ✔ | ✕ | ✕ | ✕ |
Storage typically on | Stack | Stack | Heap | Heap | Heap | Heap | Stack | Stack/Heap | Heap |
Stable iterators? | N/A | N/A | ✕ | N/A | N/A | N/A | (✔) | ✕ | ✔ |
Constraint on element type | ✕ | ✕ | ✕ | ✕ | ✔ | ✕ | ✕ | ✕ | ✕ |
Template parameter legend:
- A for allocator
- T for element type
- N for size in number of elements
- C for capacity in number of elements
- O for options
Finally, an interesting but less popular vector-like container is the "veque", or deque-vector amalgam.