Create and Delete

Below, we examine the different methods available for constructing/destroying containers with particular parameters.

You can construct each container by a multitude of constructors. To delete all elements of a container cont, you can use cont.clear(). It makes no difference if you create a container, if you delete them or if you add or remove elements. Each time the container takes care of the memory management.

The table shows you the constructors and destructors of a container. A std:vector stands for the rest of them.

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 neither be created with a range nor with an initialiser list. However, you can initialize a std::array with an aggregate initialization. Also, std::array has no method for removing its elements.

Now I can use the different constructors on the different containers.

Get hands-on with 1000+ tech skills courses.