- In C++, vectors are used to store elements of similar data types. However, unlike arrays, the size of a vector can grow dynamically. That is, we can change the size of the vector during the execution of a program as per our requirements.
- Vectors are part of the C++ Standard Template Library. To use vectors, we need to include the vector header file in our program.
std::vector<T> vector_name;
The type parameter <T> specifies the type of the vector. It can be any primitive data type such as int, char, float, etc.
Here, num is the name of the vector. we have not specified the size of the vector during the declaration. This is because the size of a vector can grow dynamically so it is not necessary to define it.
A Vector container in STL provides us with various useful functions.
- Modifiers
- Iterators
- Capacity
- push_back(): The function pushes the elements into a vector from the back. If the type of object passed as a parameter in the push_back() is not same as that of the vector an exception is thrown.
- assign(): It assigns a new value to the vector elements by replacing old ones.
- pop_back(): The pop_back() function is used to pop or remove elements from a vector from the back. It reduces the size of the vector by one element.
- insert(): This function inserts new elements before the element before the position pointed by the iterator. We can also pass a third argument count, that counts the number of times the element is to be inserted before the pointed position.
- erase(): erase() function is used to remove elements from a container from the sp
- swap(): swap() function is used to swap the contents of one vector with another vector of the same type. Sizes may differ.
- clear(): clear() function is used to remove all the elements of the vector container
- begin(): This function returns an iterator pointing to the first element in the vector.
- end(): The end() function returns an iterator pointing to the last element in the vector.
- size(): This function returns the number of elements in the vector.
- max_size(): The max_size() function returns the maximum number of elements that the vector can hold.
- capacity(): The capacity() function returns the size of the storage space currently allocated to the vector expressed as number of elements based on the memory allocated to the vector.
- resize(): This function resizes the container so that it contains ‘n’ elements. If the current size of the vector is greater than n then the back elements are removed from the vector and id the current size is smaller than n then extra elements are inserted at the back of the vector.
- empty(): Returns whether the container is empty, it return true if vector is empty else returns false.
Good explanation