Vector
In the world of programming, a vector is a dynamic array that can grow or shrink in size at runtime. It is one of the most commonly used data structures in C++ and provides several important features.
The vector in C++ is defined in the <vector>
header and is part of the Standard Template Library (STL). It is implemented as a template class, allowing us to create vectors of different types, such as int
, double
, or even custom classes.
Creating a Vector
To create a vector, we need to include the <vector>
header and declare a vector object with the desired type, followed by the name.
Here's an example of creating a vector of integers:
1#include <iostream>
2#include <vector>
3
4int main() {
5 // Declare a vector of integers
6 std::vector<int> numbers;
7
8 // ...
9}
Adding Elements to a Vector
We can add elements to a vector using the push_back()
function, which adds the element to the end of the vector. The vector automatically grows in size as we add elements.
Here's an example of adding elements to a vector:
1// Add elements to the vector
2numbers.push_back(10);
3numbers.push_back(20);
4numbers.push_back(30);
xxxxxxxxxx
int main() {
// Declare a vector of integers
std::vector<int> numbers;
// Add elements to the vector
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
// Print the elements
std::cout << "Vector elements: ";
for (int i = 0; i < numbers.size(); i++) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
return 0;
}