6. C++ Standard Template Library (STL): Vectors & Maps
Comprehensive Guide: std::string, std::vector dynamic arrays, std::map key-value pairs & std::set unique elements
Module 1: C++ std::vector Dynamic Arrays
Self-resizing dynamic array container in C++ Standard Template Library.
🇬🇧 English Definition
std::vector is a sequence container representing a dynamic array that automatically resizes itself when elements are appended or removed.
🇮🇳 Hinglish Definition
std::vector ek dynamic array hota hai jiska size data aane par apne aap badhta chala jata hai. push_back() se data add hota hai.
Core Concepts & Rules
- Add element: vec.push_back(val);
- Get element count: vec.size();
- Access element: vec[index] or vec.at(index).
🔍 Line-by-Line Code Breakdown
- Line 1: Include vector container header.
- Line 4-6: Declare vector
nums and push values 10, 20, 30. - Line 7-9: Iterate vector using range-based loop printing elements.
using namespace std;
int main() {
vector<int> nums;
nums.push_back(10);
nums.push_back(20);
nums.push_back(30);
cout << "Vector Size: " << nums.size() << endl;
cout << "Vector Items: ";
for (int x : nums) cout << x << " ";
cout << endl;
return 0;
}
Module 2: C++ std::map Key-Value Dictionary
Associative containers storing sorted key-value pairs.
🇬🇧 English Definition
std::map is a sorted associative container that stores key-value pairs with unique keys using self-balancing Red-Black trees.
🇮🇳 Hinglish Definition
std::map me data Key-Value pair me store hota hai (jaise Dictionary). Har Key unique hoti hai aur keys sorted order me rehti hai.
Core Concepts & Rules
- Insertion: studentMap['Gagan'] = 99;
- Lookup: studentMap['Gagan'] returns 99.
- Iteration: for (auto const &[key, val] : studentMap) (C++17 structured binding).
🔍 Line-by-Line Code Breakdown
- Line 4-6: Declare map
marks and assign keys 'Math' and 'Physics'. - Line 7-9: Loop through map printing key and value.
using namespace std;
int main() {
map<string, int> marks;
marks["Math"] = 95;
marks["Physics"] = 90;
for (auto const &pair : marks) {
cout << pair.first << ": " << pair.second << " Marks" << endl;
}
return 0;
}