Introduction to Vectors in C++

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.

The Basics of Vectors

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:

#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:

std::vector<int> myVector; // Declares a vector of integers named myVector

You can use the following options to initialize a vector:

// Initialization with a specified size and default values (0s)
std::vector<int> myVector2(5);

// Initialization with a specified size and a specified value
std::vector<int> myVector3(5, 10); // Vector of size 5 with all elements set to 10

// Initialization using an initializer list
std::vector<int> myVector4 {10, 20, 30, 40, 50};

// Initialization with another vector (copy initialization)
std::vector<int> myVector5(myVector4);
Vectors and Arrays Comparison
  • 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.
Accessing and Modifying Vector Elements

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:

#include <iostream>
#include <vector>

int main() {
   std::vector<int> myVector {10, 20, 30, 40, 50};
   
   // Accessing the second element
   std::cout << myVector[1] << std::endl; // 20

   // Modifying the second element
   myVector[1] = 99; // Indexing starts from 0. Thus, the second element corresponds to index 1.

   // Accessing the modified second element
   std::cout << myVector[1] << std::endl; // 99

   return 0;
}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal