📦 C++ Vector – Stretchy Array with Superpowers
A vector in C++ is like an array that can grow and shrink as needed. It’s part of the STL (Standard Template Library), and it makes life way easier than old-school arrays.
Think of a vector as a flexible container that expands when you add more stuff. 🎒
📌 Include Vector Header
#include <vector>
🛠️ Declaring a Vector
vector<int> nums; // Empty vector of integers
vector<string> names(3); // Vector of 3 strings
vector<int> odds = {1, 3, 5}; // Initialized vector
🧪 Example: Add and Print Values
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums;
nums.push_back(10);
nums.push_back(20);
nums.push_back(30);
for (int n : nums) {
cout << n << " ";
}
return 0;
}
✨ Common Vector Functions
push_back(x)– Add an element to the endpop_back()– Remove the last elementsize()– Get number of elementsat(i)– Access element at indexi(with bounds checking)clear()– Remove all elements
🧠 Example: Using size() and at()
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> fruits = {"Apple", "Mango", "Banana"};
cout << "Total: " << fruits.size() << endl;
cout << "First: " << fruits.at(0) << endl;
return 0;
}
✅ Summary
- Vectors are dynamic arrays that grow and shrink.
- They’re part of the STL and super easy to use.
- Use functions like
push_back,pop_back,at(), andsize().