What Are Vectors in C++? | TechAmbitionX - Bilal Ahmad Khan AKA Mr. BILRED
๐ท What Are Vectors in C++?
Posted on TechAmbitionX by Mr. BILRED
✅ Definition:
A vector in C++ is a dynamic array from the Standard Template Library (STL). Unlike normal arrays, vectors can grow and shrink in size during runtime.
#include <vector>
std::vector<datatype> name;
๐ Why Use Vectors?
- Dynamic resizing ✅
- Easy to use ✅
- Built-in functions ✅
- Safe access with
.at()
It works just like [ ], but with built-in bounds checking. ✅
๐ง Common Methods:
Method | Description |
---|---|
push_back(x) | Adds element x to the end |
pop_back() | Removes the last element |
size() | Returns the number of elements |
empty() | Checks if vector is empty |
clear() | Removes all elements |
at(index) | Safe access to element at index |
begin(), end() | Used for iterating |
๐ง How It Works Internally:
Vectors store elements in a dynamic array. When they run out of space, they automatically:
- Create a new, larger array
- Copy all elements to the new array
- Delete the old one
push_back()
fast most of the time, but occasionally slow due to reallocation.
๐งช Code Example:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers;
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
numbers.pop_back(); // removes 30
for (int i = 0; i < numbers.size(); ++i) {
cout << numbers[i] << " ";
}
return 0;
}
Output:
10 20
๐ Real-World Analogy:
A vector is like a flexible backpack: Start small, but as you add books (elements), it automatically upgrades to a bigger size behind the scenes. You don’t have to do it manually.
⚠️ When Not to Use Vectors?
Scenario | Better Option |
---|---|
Fast insert/delete in middle | list or deque |
Key-value pair storage | map or unordered_map |
Fixed size known at compile-time | array |
๐ Final Thoughts by Mr. BILRED:
“Vectors give you power and flexibility — but with great power comes great memory management. Know your tools, know when to use them.”
๐ Bonus GitHub Snippet:
๐ GitHub: VectorExampleByBilred
Base64: T2ggbWFuLCBOSUNFLCB5b3UgdHJpZWQgdG8gZGVjb2RlIG1lISBHcmVhdCB3b3JrIGJ0dy4uLg==
Disclaimer:
Outcomes and decisions are yours to own.
AI has been used to assist in creating this content. If any errors are found, please contact Bilal Ahmad Khan AKA Mr. BILRED ASAP.
GitHub: Bilal Ahmad Khan
My Notes:
- AppliedPhysicsNotesByBilred
- CalculusNotesByBilred
- CppNotes
Comments
Post a Comment