cpp-que-son-vector

What are Vectors in C++ and How to Use Them

  • 8 min

In C++, a vector is a collection that implements a dynamic size array (meaning it adjusts its size automatically as needed).

The std::vector class in the C++ standard library provides this implementation. Unlike traditional arrays, vectors allow for the addition and removal of elements.

If you want to learn more, check out the Introduction to Programming Course

Vector Declaration

To declare a vector in C++, the following syntax is used:

#include <vector>

std::vector<type> vectorName;
Copied!
  • type: This is the data type the vector will contain, such as int, double, std::string, etc.
  • vectorName: This is the identifier for the vector.

For example, to declare a vector of integers:

#include <vector>

std::vector<int> numbers;
Copied!

Creating and Initializing Vectors

Once a vector is declared, we must initialize it before using it.

You can create an empty vector and add elements to it later:

std::vector<int> numbers; // Empty vector
Copied!

You can initialize a vector with a specific size, where all elements are initialized to a default value (usually 0 for numeric types):

std::vector<int> numbers(5); // Vector with 5 elements, all initialized to 0
Copied!

To initialize a vector with specific values, you can use the following syntax:

std::vector<int> numbers = {1, 2, 3, 4, 5}; // Vector with values 1, 2, 3, 4, 5
Copied!

You can also initialize a vector with a specific size and an initial value for all elements:

std::vector<int> numbers(5, 10); // Vector with 5 elements, all initialized to 10
Copied!

Basic Usage of Vectors

Accessing Elements

Elements of a vector can be accessed using indices, starting from 0:

std::vector<int> numbers = {1, 2, 3, 4, 5};

int firstNumber = numbers[0]; // firstNumber will be 1
std::cout << "The first number is: " << firstNumber << std::endl;
Copied!

Alternatively, we can use the at method, which provides safe access to elements (throwing an exception if the index is out of bounds).

int second_element = numbers.at(1);
Copied!

Modifying Elements

You can modify the elements of a vector by assigning new values to specific indices:

std::vector<int> numbers = {1, 2, 3, 4, 5};

numbers[1] = 20; // The second element of the vector will now be 20
std::cout << "The modified second number is: " << numbers[1] << std::endl;
Copied!

Adding Elements to a Vector

To add elements to the end of the vector, use the push_back method:

std::vector<int> numbers = {1, 2, 3};
numbers.push_back(4); // Adds the number 4 to the end of the vector

std::cout << "Vector after adding an element: ";
for (int num : numbers) {
    std::cout << num << " ";
}
std::cout << std::endl;
Copied!

Removing Elements from a Vector

To remove an element from the end of the vector, use the pop_back method:

std::vector<int> numbers = {1, 2, 3, 4};
numbers.pop_back(); // Removes the last element (4)

std::cout << "Vector after removing an element: ";
for (int num : numbers) {
    std::cout << num << " ";
}
std::cout << std::endl;
Copied!

You can also remove an element at a specific position using the erase method:

std::vector<int> numbers = {1, 2, 3, 4, 5};
numbers.erase(numbers.begin() + 2); // Removes the third element (3)

std::cout << "Vector after removing an element at position 2: ";
for (int num : numbers) {
    std::cout << num << " ";
}
std::cout << std::endl;
Copied!

Inserting Elements at a Specific Position

To insert an element at a specific position in the vector, use the insert method:

std::vector<int> numbers = {1, 2, 4, 5};
numbers.insert(numbers.begin() + 2, 3); // Inserts the number 3 at position 2

std::cout << "Vector after inserting an element at position 2: ";
for (int num : numbers) {
    std::cout << num << " ";
}
std::cout << std::endl;
Copied!

Useful Properties and Methods

C++ vectors offer several properties and methods to efficiently manipulate and access their elements:

size Property

The size() function returns the number of elements in the vector:

std::vector<int> numbers = {1, 2, 3, 4, 5};
std::cout << "Number of elements in the vector: " << numbers.size() << std::endl;
Copied!

capacity Method

The capacity() function returns the current capacity of the vector, that is, the number of elements it can hold before needing a reallocation:

std::vector<int> numbers = {1, 2, 3};
std::cout << "Vector capacity: " << numbers.capacity() << std::endl;
Copied!

clear Method

The clear() method removes all elements from the vector:

std::vector<int> numbers = {1, 2, 3, 4, 5};
numbers.clear(); // Removes all elements

std::cout << "Number of elements after clear: " << numbers.size() << std::endl;
Copied!

empty Method

Checks if the vector is empty.

if (numbers.empty()) {
    std::cout << "The vector is empty" << std::endl;
}
Copied!

sort Method

To sort the elements of a vector, you can use the sort function from the <algorithm> library:

std::vector<int> numbers = {5, 3, 1, 4, 2};
std::sort(numbers.begin(), numbers.end()); // Sorts the vector in ascending order

std::cout << "Sorted vector: ";
for (int num : numbers) {
    std::cout << num << " ";
}
std::cout << std::endl;
Copied!

reverse Method

To reverse the order of elements, you can use the reverse function from the <algorithm> library:

std::vector<int> numbers = {1, 2, 3, 4, 5};
std::reverse(numbers.begin(), numbers.end()); // Reverses the order of elements

std::cout << "Reversed vector: ";
for (int num : numbers) {
    std::cout << num << " ";
}
std::cout << std::endl;
Copied!

resize Method

Changes the size of the vector.

numbers.resize(10);  // Resizes the vector to 10 elements
Copied!

reserve Method

Reserves space for at least the specified number of elements.

numbers.reserve(20);  // Reserves space for 20 elements
Copied!

shrink_to_fit Method

Resizes the vector’s capacity to match its size.

numbers.shrink_to_fit();
Copied!

Practical Examples