Back to C++
2025-12-227 min read

C++ <vector>

Learn C++ <vector> step by step with clear examples and exercises.

Title: Mastering C++ Vectors: A full guide for Efficient Programming

Why This Matters

In this tutorial, we will delve into the powerful ` library in C++, a fundamental tool that simplifies dynamic array management and enhances code efficiency. Understanding ` is crucial for competitive programming, real-world projects, and interview preparation as it allows you to handle dynamic data structures effectively.

A vector is a dynamic array-like container that can grow and shrink as needed during runtime. It provides several advantages over traditional arrays:

  1. Dynamic size: Vectors automatically manage their size, eliminating the need for manual memory allocation and deallocation.
  2. Efficient insertion and deletion: Vectors offer constant-time (O(1)) complexity for most operations, making them more efficient than traditional arrays.
  3. Standard library support: The `` class is part of the C++ Standard Template Library (STL), providing a robust and reliable solution for dynamic array management.

Prerequisites

Before diving into the core concept of C++ vectors, ensure you have a solid grasp of:

  1. Basic C++ syntax and control structures (if, for, while)
  2. Understanding of classes and objects
  3. Familiarity with standard input/output functions (cin, cout)
  4. Concepts of memory allocation and deallocation in C++
  5. Understand how to use iterators and algorithms from the STL
  6. Be familiar with the concept of exceptions and error handling
  7. Knowledge of Standard Template Library (STL) containers such as std::list, std::deque, and std::array

Core Concept

A vector is a dynamic array-like container that can grow and shrink as needed during runtime. It provides several advantages over traditional arrays:

  1. Dynamic size: Vectors automatically manage their size, eliminating the need for manual memory allocation and deallocation.
  2. Efficient insertion and deletion: Vectors offer constant-time (O(1)) complexity for most operations, making them more efficient than traditional arrays.
  3. Standard library support: The `` class is part of the C++ Standard Template Library (STL), providing a robust and reliable solution for dynamic array management.
  4. Flexibility: Vectors can store elements of any data type as long as it has a default constructor, copy constructor, and destructor.
  5. Iterators: Vectors support bidirectional iterators, allowing you to traverse the container easily and efficiently.
  6. Algorithms: Many STL algorithms are designed to work with vectors, making it simple to sort, search, and manipulate vector data.
  7. Exception safety: The `` class provides exception-safe behavior during memory operations, ensuring your program remains stable even in the face of errors.

Creating a Vector

To create a vector, simply include the ` header and declare a variable of type std::vector`. For example:

#include <vector>

int main() {
std::vector<int> myVector;
// myVector is now an empty vector of integers
}

Adding Elements to a Vector

You can add elements to a vector using the push_back() function:

myVector.push_back(5); // adds 5 to the end of myVector

Accessing Vector Elements

Access individual elements in a vector by their index, similar to traditional arrays:

int firstElement = myVector[0]; // accesses the first element in myVector

Vector Size and Capacity

The size() function returns the number of elements currently stored in the vector, while the capacity() function tells you how many elements the vector can hold without reallocating memory.

Iterators

Vectors support bidirectional iterators, allowing you to traverse the container easily and efficiently:

for (auto it = myVector.begin(); it != myVector.end(); ++it) {
std::cout << *it << " "; // print each number on a separate line
}

Algorithms

Many STL algorithms are designed to work with vectors, making it simple to sort, search, and manipulate vector data:

#include <algorithm>

std::sort(myVector.begin(), myVector.end()); // sorts the vector in ascending order
auto it = std::find(myVector.begin(), myVector.end(), targetValue); // locates an element within a vector

Worked Example

Let's create a simple program that reads integers from standard input and stores them in a vector until an empty line is encountered:

#include <iostream>
#include <vector>
#include <string>

int main() {
std::vector<int> numbers;
std::string input;

while (std::getline(std::cin, input) && !input.empty()) {
try {
numbers.push_back(stoi(input)); // convert string to integer and add it to the vector
} catch (const std::invalid_argument& e) {
std::cerr << "Invalid input: " << e.what() << '\n';
}
}

for (const auto& number : numbers) {
std::cout << number << " "; // print each number on a separate line
}

return 0;
}

Common Mistakes

  1. **Forgetting to include the ` header**: Always remember to include the necessary headers for using the ` library.
  2. Using subscript out of bounds: Be careful not to access elements outside the vector's valid range. Use the size() function to ensure you're within bounds.
  3. Misusing iterators: Iterators are powerful tools for manipulating vectors, but they can be confusing if not used correctly. Familiarize yourself with iterator basics and practice using them effectively.
  4. Incorrectly comparing vectors: When comparing two vectors, use the == operator instead of !=. The latter checks whether the iterators point to different locations in memory, which is usually not what you want.
  5. Ignoring capacity: Understanding a vector's capacity can help optimize your code by avoiding unnecessary reallocations and improving performance.
  6. Not handling exceptions: When dealing with user input or custom data types, always ensure that your program can handle exceptions gracefully to avoid crashes.
  7. Misusing reserve() and resize(): The reserve() function reserves memory for a vector, but does not allocate it until needed. On the other hand, the resize() function changes both the size and capacity of the vector simultaneously. Be mindful of these functions' usage to optimize your code.
  8. Confusing iterators and pointers: While iterators and pointers share some similarities, they have distinct differences in behavior and usage. Familiarize yourself with the differences to avoid common mistakes when working with vectors.

Practice Questions

  1. Write a program that takes a list of integers as input and finds the maximum and minimum values in the list.
  2. Implement a function that reverses the order of elements in a given vector.
  3. Create a program that reads a line of text, splits it into words using std::string::split(), and stores each word in a separate vector.
  4. Write a program that sorts a vector of integers in ascending order.
  5. Implement a function that merges two sorted vectors into one sorted vector.
  6. Create a program that counts the number of occurrences of each unique element in a given vector.
  7. Write a program that finds the second largest number in a vector.
  8. Implement a function that removes duplicates from a vector while maintaining its original order.
  9. Create a program that finds the kth smallest number in a sorted vector.
  10. Write a program that calculates the average of all numbers in a vector.

FAQ

  1. Why is it better to use a vector instead of an array? Vectors offer dynamic size, efficient insertion and deletion, and standard library support, making them more flexible and efficient than traditional arrays.
  2. What happens when a vector reaches its capacity? When a vector reaches its capacity, it automatically reallocates memory to accommodate additional elements. This process may incur a performance overhead due to the need for memory copying or resizing.
  3. Can I use vectors with custom data types? Yes, you can create vectors of user-defined data types by specifying the type template argument when declaring the vector. For example: std::vector.
  4. What is the time complexity of common vector operations? Most vector operations have constant-time (O(1)) complexity, with the exception of inserting elements at specific positions and erasing elements from the middle of the vector, which both have linear-time (O(n)) complexity in the worst case.
  5. How can I find the index of a specific element in a vector? Use the std::find() function to locate an element within a vector:
auto it = std::find(myVector.begin(), myVector.end(), targetValue);
if (it != myVector.end()) {
int index = std::distance(myVector.begin(), it);
}
  1. What is the difference between vector and a regular vector of booleans? A vector is a specialized container that stores bits more efficiently than a regular vector of booleans. It uses a single bit to store each boolean value, whereas a regular vector requires one byte (8 bits) for each boolean.
  2. How can I optimize my code when using vectors? To optimize your code, consider the following strategies:
  • Use reserve() to preallocate memory when you anticipate adding many elements.
  • Minimize reallocations by ensuring that the vector's capacity is sufficient for the expected number of elements.
  • Use iterators and algorithms from the STL to manipulate vectors efficiently.
  • Be mindful of exception safety when dealing with user input or custom data types.
C++ &lt;vector&gt; | C++ | XQA Learn