The vector in C++ is a container type provided by the Standard Template Library (STL). It is named a vector because it functionally resembles a dynamic array in mathematics. In mathematics, a vector is an ordered collection of numbers that can dynamically change its size. Similarly, the vector in C++ has this property, allowing it to dynamically add or remove elements as needed without manual memory management. The naming of vector reflects its ability to dynamically change size at runtime, which is similar to the concept of mathematical vectors. Additionally, vector stores elements contiguously in memory, enabling it to provide fast random access similar to arrays. For example, when using the C++ vector, you can begin with a small set of elements, but as the program runs and requires more elements, you can add more to this vector without worrying about the initial allocated space:
cpp#include <iostream> #include <vector> int main() { std::vector<int> numbers; numbers.push_back(10); // Add element 10 numbers.push_back(20); // Add element 20 std::cout << "Current vector size: " << numbers.size() << std::endl; numbers.push_back(30); // Add another element 30 std::cout << "New vector size: " << numbers.size() << std::endl; for(int num : numbers) std::cout << num << " "; // Output: 10 20 30 return 0; }
In this example, the size of vector starts at 0 and increases gradually as elements are added. This capability makes the C++ vector very flexible and powerful, suitable for various scenarios requiring dynamic array functionality.