Chapter 10C++ Tutorial~1 min read
STL — Standard Template Library
STL — Ready-made Data Structures
STL (Standard Template Library) म्हणजे C++ मध्ये built-in data structures आणि algorithms. Array ऐवजी vector, map, set, queue, stack — सगळे ready-made, efficient आणि type-safe.
Marathi Analogy
STL म्हणजे kitchen मधले appliances — toaster, mixer, microwave. प्रत्येक appliance specific task साठी optimized. Scratch पासून बनवायला नको — STL containers वापरा आणि faster code लिहा!
vector — Dynamic Array
vector — most used container
cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// vector — dynamic size array
vector<int> v = {5, 2, 8, 1, 9, 3};
vector<string> names;
// Add elements
names.push_back("Rahul");
names.push_back("Priya");
names.push_back("Amit");
// Size
cout << "Size: " << v.size() << endl; // 6
// Access
cout << v[0] << endl; // 5
cout << v.at(1) << endl; // 2 — bounds check
cout << v.front() << endl; // 5 — first
cout << v.back() << endl; // 3 — last
// Remove last
v.pop_back();
cout << "After pop: " << v.size() << endl; // 5
// Sort
sort(v.begin(), v.end());
for (auto x : v) cout << x << " ";
cout << endl; // 1 2 5 8 9
// Range-based for
for (const auto &name : names) {
cout << name << endl;
}
return 0;
}map — Key-Value Store
map — sorted key-value pairs
cpp
#include <iostream>
#include <map>
using namespace std;
int main() {
// map<key_type, value_type>
map<string, int> marks;
// Insert
marks["Rahul"] = 85;
marks["Priya"] = 92;
marks["Amit"] = 78;
// Access
cout << marks["Rahul"] << endl; // 85
// Iterate — automatically sorted by key
for (auto &pair : marks) {
cout << pair.first << ": " << pair.second << endl;
}
// Amit: 78
// Priya: 92
// Rahul: 85
// Check key exists
if (marks.count("Priya")) {
cout << "Priya found!" << endl;
}
// Erase
marks.erase("Amit");
cout << "Size: " << marks.size() << endl; // 2
return 0;
}set, stack, queue
Other common containers
cpp
#include <set>
#include <stack>
#include <queue>
// set — unique values, auto sorted
set<int> s = {5, 2, 8, 2, 1, 5}; // duplicates remove!
for (int x : s) cout << x << " ";
cout << endl; // 1 2 5 8
// stack — LIFO (Last In First Out)
stack<int> stk;
stk.push(1); stk.push(2); stk.push(3);
cout << stk.top() << endl; // 3
stk.pop();
cout << stk.top() << endl; // 2
// queue — FIFO (First In First Out)
queue<string> q;
q.push("Rahul"); q.push("Priya"); q.push("Amit");
cout << q.front() << endl; // Rahul
q.pop();
cout << q.front() << endl; // Priya✅ Key Points — लक्षात ठेवा
- ▸vector<T> — dynamic array, push_back/pop_back
- ▸map<K,V> — sorted key-value, operator[]
- ▸set<T> — unique sorted values
- ▸stack<T> — LIFO (push/pop/top)
- ▸queue<T> — FIFO (push/pop/front)
0/11 chapters पूर्ण