Create and Delete
Below, we examine the different methods available for constructing and destroying containers with particular parameters.
We can construct each container using a multitude of constructors. To delete all elements of a container cont
, use cont.clear()
. It makes no difference if you create and delete a container or if we add and remove elements. Each time the container takes care of memory management.
The table shows the constructors and destructors of a container. All these functions can be used with std:vector
.
Type | Example |
---|---|
Default | std::vector<int> vec1 |
Range | std::vector<int> vec2(vec1.begin(), vec1.end()) |
Copy | std::vector<int> vec3(vec2) |
Copy | std::vector<int> vec3= vec2 |
Move | std::vector<int> vec4(std::move(vec3)) |
Move | std::vector<int> vec4= std::move(vec3) |
Sequence (Initializer list) | std::vector<int> vec5 {1, 2, 3, 4, 5} |
Sequence (Initializer list) | std::vector<int> vec5= {1, 2, 3, 4, 5} |
Destructor | vec5.~vector() |
Delete elements | vec5.clear() |
Creation and deletion of a container
Because std::array
is generated at compile-time, there are a few things that are special. std::array
has no move constructor and can’t be created with a range or with an initializer list. However, an std::array
can be initialized with an aggregate initialization. Also, std::array
has no method for removing its elements.
Now we can use the different constructors on the different containers.
Get hands-on with 1400+ tech skills courses.