Vector in C++
Vectors in C++ are one of the containers offered to us by the STL(Standard Template Library) in C++. It stores a collection of similar-type objects in a variable-sized array.
Note: C++ provides us with objects that store a collection of elements (i.e. other objects), referred to by the term ‘containers’.
Declaration of a vector in C++
In C++, a vector is a dynamic array, meaning that its size can grow or shrink as needed during program execution. Vectors are part of the C++ Standard Template Library (STL) and are declared using the following syntax:
Where:
- std::vector is the namespace for vectors
- <data_type> is the type of data the vector will store, such as int, double, or std::string
- vector_name is the name of the vector
For example, to declare a vector of integers named numbers, you would write:
This vector can initially hold no elements, but its size can be increased or decreased as needed.
Initialization of a vector in C++
Initializing a vector in C++ involves assigning values to its elements. There are several ways to initialize a vector, including:
1. Using an initializer list:
An initializer list is a comma-separated list of values enclosed in curly braces. It is the simplest and most common way to initialize a vector.
This code initializes a vector named numbers with the values 1, 2, 3, 4, and 5.
2. Using the fill() algorithm:
The fill() algorithm fills all the elements of a vector with a specified value.
This code initializes a vector of 10 integer elements, all with the value 0.
3. Using a copy constructor:
A copy constructor creates a new vector by copying the values from an existing vector.
This code initializes a vector named numbers2 by copying the values of the vector numbers1.
4. Using an array:
An array can be used to initialize a vector.
This code initializes a vector named numbers using the elements of the array arr.
5. Using a range-based for loop:
A range-based for loop can be used to initialize a vector with values from another container.
This code initializes a vector named numbers by copying the values from the list values.
Basic Vector Operations
some of the basic vector operations in C++ are:
- Accessing Elements: You can access elements of a vector using either its index or an iterator. Indexing uses square brackets [] and an index value, while iterators provide a pointer-like interface to traverse the vector.
- Modifying Elements: You can modify the values of vector elements using either indexing or iterators. Both methods allow you to change the value at a specific position in the vector.
- Adding Elements: There are several ways to add new elements to a vector. The most common methods are using the push_back() and insert() functions.
- Removing Elements: You can remove elements from a vector using the erase() and pop_back() functions.
- Checking Size and Emptiness: The size() function returns the number of elements in the vector, while the empty() function checks whether the vector is empty or not.
- Resizing the Vector: You can resize a vector using the resize() function, which can either increase or decrease the vector's capacity.
- Clearing the Vector: The clear() function removes all elements from the vector, effectively emptying it.
Various Functions in Vectors
Iterators:
Function | Description | Example Code |
---|---|---|
begin() | Iterator to beginning | auto it = a.begin(); |
end() | Iterator to end | auto it = a.end(); |
rbegin() | Reverse iterator to reverse beginning | auto rit = a.rbegin(); |
rend() | Reverse iterator to reverse end | auto rit = a.rend(); |
cbegin() | Const_iterator to beginning | auto cit = a.cbegin(); |
cend() | Const_iterator to end | auto cit = a.cend(); |
crbegin() | Const_reverse_iterator to reverse beginning | auto crit = a.crbegin(); |
crend() | Const_reverse_iterator to reverse end | auto crit = a.crend(); |
Example Code for Visualizing the use of Iterators:
Output:
Capacity:
Function | Description | Example Code |
---|---|---|
size() | Return size | size_t size = a.size(); |
max_size() | Return maximum size | size_t maxSize = a.max_size(); |
resize(n) | Change size | a.resize(10); |
capacity() | Return size of allocated storage capacity | size_t capacity = a.capacity(); |
empty() | Test whether vector is empty | bool isEmpty = a.empty(); |
reserve() | Request a change in capacity | a.reserve(100); |
shrink_to_fit() | Shrink to fit | a.shrink_to_fit(); |
Example Code for Visualizing the use of Capacity functions:
Output:
Modifiers:
Function | Description | Example Code |
---|---|---|
assign() | Assign vector content | a.assign(4, 7); |
push_back() | Add element at the end | a.push_back(10); |
pop_back() | Delete last element | a.pop_back(); |
insert() | Insert elements | a.insert(a.begin(), 3); |
erase() | Erase elements | a.erase(a.begin()); |
swap() | Swap content | a.swap(b); |
clear() | Clear content | a.clear(); |
emplace() | Construct and insert element | a.emplace(a.begin(), 42); |
emplace_back() | Construct and insert element at the end | a.emplace_back(42); |
Example Code for Visualizing the use of Modifiers :
Output:
Element access:
Function | Description | Example Code |
---|---|---|
operator[] | Access element | int element = a[0]; |
at() | Access element with bounds checking | int element = a.at(0); |
front() | Access first element | int firstElement = a.front(); |
back() | Access last element | int lastElement = a.back(); |
data() | Access data as a pointer | int* dataPtr = a.data(); |
Example Code for Visualizing the use of Element access functions:
Output:
Allocators Function in Vector C++
Allocators are objects that manage the dynamic allocation and deallocation of memory for containers like vectors. In C++, vectors provide a single function called get_allocator() that allows you to access the allocator associated with a vector. This allocator can be used to allocate custom memory chunks or to modify the allocator's behavior.
When to use Vectors?
We can use Vectors in the following circumstances:
It is advisable to use vectors when data are consistently changing.
If the size of data is unknown then it is advisable to use vectors.
It is advisable to use vectors when elements are not predefined.
Compared to arrays there are more ways to copy vectors.
Vector of Vectors in C++ STL
In C++ STL, you can create a vector of vectors to represent a two-dimensional array or a matrix. This is often useful when dealing with a grid-like structure or a table. Here's an example of how to create and use a vector of vectors:
Output
In this example:
- std::vector<std::vector<int>> matrix; declares a vector of vectors of integers.
- matrix.resize(rows); resizes the outer vector to the number of rows.
- matrix[i].resize(columns); resizes each inner vector to the number of columns.
- The matrix is then filled with values, and its elements are printed.
Advantages of Vectors
- Dynamic Nature: Vectors can dynamically resize based on the number of elements.
- Easy Insertion and Deletion: Elements can be easily inserted or deleted in vectors.
- Storage of Multiple Objects: Vectors can store multiple objects of the same type.
- Simple Copying: Copying vectors is straightforward using the assignment operator.
Disadvantages of Vectors
- High Memory Consumption: Vectors may consume more memory compared to other data structures.
- Lack of Direct Indexing: Vectors do not provide direct indexing, impacting random access efficiency.
- Non-Contiguous Memory: The memory allocated for vectors may not be contiguous, affecting cache performance.
Conclusion
It can be concluded that vectors offer us a lot more than arrays and in order to excel in programming, one has to study the STL, especially the vector class.
Reasons for such an abundant usage of vectors are as follows :
- Dynamic nature (the size of a vector can be adjusted accordingly).
- Since vectors offer us dynamic arrays. We are able to have unique-sized arrays even in multidimensional arrays.
- There are multiple ways to copy one vector to another.
- Easy to pass as an argument.
- Easy initialisation with constant values.
- Multiple member functions for user's convenience.
- Easy to clear the vector for saving memory.
A vector is always a better option over arrays and linked lists in storing and managing bulky and dynamic data in our program.