Welcome! Today's lesson focuses on vectors, which are dynamic equivalents of arrays in C++. We'll discuss how to declare, initialize, access, and manipulate them, and we'll delve into other unique elements.
Vectors are dynamic arrays that form part of the C++ Standard Library. Unlike arrays, which require a pre-defined size, vectors allow elements to be populated as needed, resizing as they grow.
To use vectors, you must include the vector library:
C++1#include <vector>
This library provides the necessary functionality to work with vectors.
Vectors are declared using the std::vector
template followed by the type of elements they will store. Here's the anatomy of a vector declaration:
C++1std::vector<int> myVector; // Declares a vector of integers named myVector
You can use the following options to initialize a vector:
C++1// Initialization with a specified size and default values (0s) 2std::vector<int> myVector2(5); 3 4// Initialization with a specified size and a specified value 5std::vector<int> myVector3(5, 10); // Vector of size 5 with all elements set to 10 6 7// Initialization using an initializer list 8std::vector<int> myVector4 {10, 20, 30, 40, 50}; 9 10// Initialization with another vector (copy initialization) 11std::vector<int> myVector5(myVector4);
- Static vs. Dynamic Size: Arrays have a fixed size declared at compile time. Vectors can grow and shrink dynamically as elements are added or removed.
- Memory Management: Arrays have contiguous memory allocation. Vectors handle memory automatically, resizing and managing space as needed.
- Functionality: Vectors provide built-in functions like
push_back()
,pop_back()
,insert()
,erase()
, etc., which are not available for arrays.
Like arrays, vectors store elements in contiguous storage locations, allowing efficient access using indices. Elements can be accessed like array elements (vector[index]
). Indices can also be used to modify vector values.
Let's demonstrate how to initialize and modify values:
C++1#include <iostream> 2#include <vector> 3 4int main() { 5 std::vector<int> myVector {10, 20, 30, 40, 50}; 6 7 // Accessing the second element 8 std::cout << myVector[1] << std::endl; // 20 9 10 // Modifying the second element 11 myVector[1] = 99; // Indexing starts from 0. Thus, the second element corresponds to index 1. 12 13 // Accessing the modified second element 14 std::cout << myVector[1] << std::endl; // 99 15 16 return 0; 17}
Vectors support several built-in operations, including size()
, empty()
, clear()
. These operations streamline the process of working with vectors.
Let's demonstrate a few of these operations:
C++1#include <iostream> 2#include <vector> 3 4int main() { 5 std::vector<int> myVector {10, 20, 30, 40, 50}; 6 7 // Check if the vector is empty 8 if (myVector.empty()) { 9 std::cout << "Vector is empty!" << std::endl; 10 } else { 11 std::cout << "Vector is not empty!" << std::endl; 12 } 13 14 // Clear the vector 15 myVector.clear(); // Removes all elements. 16 17 // Check the size of the vector after clearing 18 std::cout << "Size after clear operation: " << myVector.size() << std::endl; // 0 19 20 return 0; 21}
- size(): Returns the number of elements in the vector.
- empty(): Checks whether the vector is empty or not.
- clear(): Removes all elements from the vector.
The push_back()
function appends elements to the end of the vector, allowing us to populate an uninitialized vector.
C++1#include <iostream> 2#include <vector> 3 4int main() { 5 std::vector<int> myVector; 6 7 // Using push_back to populate the vector 8 myVector.push_back(10); 9 myVector.push_back(20); 10 myVector.push_back(30); 11 12 // Printing the vector 13 for (int i = 0; i < myVector.size(); i++) { 14 std::cout << myVector[i] << " "; // 10 20 30 15 } 16 std::cout << std::endl; 17 18 return 0; 19}
The pop_back()
function removes the last element of the vector.
C++1#include <iostream> 2#include <vector> 3 4int main() { 5 std::vector<int> myVector {10, 20, 30, 40, 50}; 6 7 // Remove the last element 8 myVector.pop_back(); 9 10 // Printing the vector 11 for (int i = 0; i < myVector.size(); i++) { 12 std::cout << myVector[i] << " "; // 10 20 30 40 13 } 14 std::cout << std::endl; 15 16 return 0; 17}
Similar to arrays, we can traverse a vector to access or modify its elements using a for
loop. A more modern and concise approach is using the range-based for
loop, which eliminates the need for explicitly iterating through array indexes:
C++1#include <iostream> 2#include <vector> 3 4int main() { 5 std::vector<int> newVector {10, 20, 30, 40, 50}; 6 7 for(int element : newVector) 8 std::cout << element << " "; // 10 20 30 40 50 9 std::cout << std::endl; 10 11 return 0; 12}
Vectors in C++ are type-safe, meaning they can only store elements of a single data type. Attempting to use mixed data types will result in a compile-time error:
C++1#include <iostream> 2#include <vector> 3 4int main() { 5 // The following line will cause a compile-time error: 6 // std::vector<int> myVector {10, 20.5, 30}; 7 8 return 0; 9}
Congratulations! You have traversed the fundamentals of vectors in C++. Up next are practice exercises designed to instill your understanding of vectors in C++. Enjoy these engaging exercises!