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;
- type: This is the data type the
vectorwill contain, such asint,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;
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
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
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
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
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;
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);
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;
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;
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;
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;
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;
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;
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;
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;
empty Method
Checks if the vector is empty.
if (numbers.empty()) {
std::cout << "The vector is empty" << std::endl;
}
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;
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;
resize Method
Changes the size of the vector.
numbers.resize(10); // Resizes the vector to 10 elements
reserve Method
Reserves space for at least the specified number of elements.
numbers.reserve(20); // Reserves space for 20 elements
shrink_to_fit Method
Resizes the vector’s capacity to match its size.
numbers.shrink_to_fit();
Practical Examples
Calculate the sum of elements in a vector
This example uses a for loop to calculate the sum of the elements in a vector:
#include <vector>
#include <iostream>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : numbers) {
sum += num;
}
std::cout << "The sum of the elements is: " << sum << std::endl;
return 0;
}
Filter elements of a vector
This example uses a for loop to filter the even elements of a vector:
#include <vector>
#include <iostream>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::vector<int> evenNumbers;
for (int num : numbers) {
if (num % 2 == 0) {
evenNumbers.push_back(num);
}
}
std::cout << "Even numbers: ";
for (int num : evenNumbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Find the maximum value in a vector
This example uses the max_element function from the <algorithm> library to find the maximum value in a vector:
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
int maximum = *std::max_element(numbers.begin(), numbers.end());
std::cout << "The maximum value is: " << maximum << std::endl;
return 0;
}
Count how many elements meet a condition
This example uses the count_if function from the <algorithm> library to count how many elements in a vector are greater than a specific value:
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
int counter = std::count_if(numbers.begin(), numbers.end(), [](int num) { return num > 3; });
std::cout << "There are " << counter << " elements greater than 3" << std::endl;
return 0;
}
Remove elements from a vector
This example uses the remove_if function from the <algorithm> library to remove all odd elements from a vector:
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
numbers.erase(std::remove_if(numbers.begin(), numbers.end(), [](int num) { return num % 2 != 0; }), numbers.end());
std::cout << "Remaining numbers: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
