7. C++ STL Containers & std::sort Algorithms
Comprehensive Guide: std::stack, std::queue, std::priority_queue, std::sort & binary_search algorithms
Module 1: C++ std::stack & std::queue Containers
LIFO and FIFO container adapters in C++ Standard Template Library.
🇬🇧 English Definition
std::stack provides LIFO access while std::queue provides FIFO queue operations wrapping underlying sequence containers.
🇮🇳 Hinglish Definition
std::stack (LIFO) aur std::queue (FIFO) standard containers hote hai jo push(), pop(), top(), front() methods provide karte hai.
Core Concepts & Rules
- std::stack: push(), pop(), top(), empty().
- std::queue: push(), pop(), front(), back().
🔍 Line-by-Line Code Breakdown
- Line 4-6: Declare stack
s and push 'Chapter 1' and 'Chapter 2'. - Line 7: s.top() returns 'Chapter 2'.
💻 Practical C++ Code Example - C++ std::stack & std::queue Containers
using namespace std;
int main() {
stack<string> st;
st.push("Chapter 1");
st.push("Chapter 2");
cout << "Top Stack Item: " << st.top() << endl;
st.pop();
cout << "Top After Pop: " << st.top() << endl;
return 0;
}
📤 Compiled C++ Output:
Top Stack Item: Chapter 2
Top After Pop: Chapter 1
Module 2: C++ STL Algorithms: std::sort & std::reverse
Ultra-fast optimized hybrid IntroSort sorting algorithms in
🇬🇧 English Definition
std::sort uses a hybrid IntroSort algorithm (QuickSort + HeapSort + InsertionSort) achieving guaranteed O(N log N) performance.
🇮🇳 Hinglish Definition
std::sort(vec.begin(), vec.end()) se array ya vector super-fast O(N log N) speed me sort ho jata hai.
Core Concepts & Rules
- Ascending Sort: sort(v.begin(), v.end());
- Descending Sort: sort(v.begin(), v.end(), greater
());
🔍 Line-by-Line Code Breakdown
- Line 2: Initialize vector
v = {50, 10, 40, 20}. - Line 3: Execute sort(v.begin(), v.end()).
- Line 4-6: Prints sorted vector values.
💻 Practical C++ Code Example - C++ STL Algorithms: std::sort & std::reverse
using namespace std;
int main() {
vector<int> v = {50, 10, 40, 20};
sort(v.begin(), v.end());
cout << "STL Sorted Vector: ";
for (int x : v) cout << x << " ";
cout << endl;
return 0;
}
📤 Compiled C++ Output:
STL Sorted Vector: 10 20 40 50