C++ - Vectors Part 1: Introduction to Vectors
Vectors are part of the std namespace and offer dynamic resizing capabilities, unlike static arrays. To use vectors, include the <vector> header.
Examples and Explanation
Declaring and Initializing Vectors
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec; // Empty vector
std::vector<int> vec2 = {1, 2, 3}; // Initialized with values
std::vector<int> vec3(5, 10); // 5 elements, each initialized to 10
return 0;
}
Explanation: Vectors can be initialized empty, with specific values, or with a specified size and default value.
Accessing Elements
vec2[0] = 5;
std::cout << vec2[0]; // Output: 5
Explanation: Elements can be accessed using the [] operator or the .at() method, which provides bounds checking.
Adding Elements
vec.push_back(4); // Add 4 to the end of the vector
Explanation: The push_back() method appends elements to the vector, automatically resizing it.