Skip to main content

C Plus Plus

std::vector in C++

Master std::vector in C++: Efficient dynamic arrays with fast access and versatile operations.

Introduction to std::vector

C++ is a powerful programming language widely used in software development. One of its most essential components is the Standard Template Library (STL), which includes the versatile std::vector. This dynamic array can grow and shrink in size, providing a flexible way to manage collections of data.

What is std::vector?

std::vector is a sequence container in C++ that allows dynamic resizing. Unlike arrays, which have a fixed size, vectors can expand or contract as needed. This flexibility makes std::vector a popular choice for storing collections of data.

Key Features of std::vector

  • Dynamic Size: Can grow or shrink as needed.
  • Contiguous Memory: Elements are stored in contiguous memory locations, enabling efficient access and cache performance.
  • Automatic Memory Management: Handles memory allocation and deallocation automatically.
  • Range Checking: Provides at() function for bounds-checked access.

How to Declare and Initialize a std::vector

Here are some basic ways to declare and initialize a vector:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec1; // Empty vector of integers
    std::vector<int> vec2(10); // Vector of 10 integers, initialized to 0
    std::vector<int> vec3(10, 5); // Vector of 10 integers, initialized to 5
    std::vector<int> vec4 = {1, 2, 3, 4, 5}; // Vector initialized with list of integers

    return 0;
}

Basic Operations on std::vector

Adding Elements

Elements can be added to the end of the vector using the push_back method:

vec1.push_back(1); // Adds 1 to the end of vec1
vec1.push_back(2); // Adds 2 to the end of vec1

Accessing Elements

Elements in a vector can be accessed using the [] operator or the at method:

int firstElement = vec4[0]; // Access first element (no bounds checking)
int secondElement = vec4.at(1); // Access second element (with bounds checking)

Removing Elements

Elements can be removed from the end of the vector using the pop_back method:

vec1.pop_back(); // Removes last element from vec1

Iterating Over Elements

You can use a range-based for loop or an iterator to iterate over the elements of a vector:

for (int value : vec4) {
    std::cout << value << " ";
}

for (std::vector<int>::iterator it = vec4.begin(); it != vec4.end(); ++it) {
    std::cout << *it << " ";
}

Advanced Operations on std::vector

Inserting Elements