Skip to content

nageshnnazare/cpp-know-hows

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

C++ Standard Template Library (STL) Tutorial

Complete Guide to C++23 STL

┌─────────────────────────────────────────────────────────────┐
│                    C++ STL ECOSYSTEM                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌─────────────┐   ┌─────────────┐   ┌─────────────┐        │
│  │ CONTAINERS  │   │  ITERATORS  │   │ ALGORITHMS  │        │
│  │             │◄──┤             │◄──┤             │        │
│  │  Data       │   │  Access     │   │  Process    │        │
│  │  Storage    │   │  Interface  │   │  Data       │        │
│  └─────────────┘   └─────────────┘   └─────────────┘        │
│        │                   │                  │             │
│        └───────────────────┴──────────────────┘             │
│                            │                                │
│                     ┌──────▼──────┐                         │
│                     │  ALLOCATORS │                         │
│                     │  & FUNCTORS │                         │
│                     └─────────────┘                         │
└─────────────────────────────────────────────────────────────┘

Overview

The C++ Standard Template Library (STL) is a powerful collection of template classes and functions that provide generic implementations of common data structures and algorithms. This tutorial covers everything from C++98 to the latest C++23 standard.

Tutorial Structure

Part 0: Foundations

  • Classes and Objects
  • Encapsulation (data hiding and access control)
  • Inheritance (single and multiple)
  • Polymorphism (compile-time and runtime)
  • Abstraction (interfaces and abstract classes)
  • Virtual functions and dynamic binding
  • Constructors and destructors
  • Complete practical banking system example
  • Important gotchas and hunches for each OOP concept

Part I: STL Fundamentals

  • std::vector - Dynamic array
  • std::deque - Double-ended queue
  • std::list - Doubly-linked list
  • std::forward_list - Singly-linked list
  • std::array - Fixed-size array
  • std::set / std::multiset - Ordered unique/multiple elements
  • std::map / std::multimap - Ordered key-value pairs
  • std::unordered_set / std::unordered_multiset - Hash-based sets
  • std::unordered_map / std::unordered_multimap - Hash-based maps
  • std::stack - LIFO data structure
  • std::queue - FIFO data structure
  • std::priority_queue - Heap-based priority queue
  • Iterator categories
  • Iterator operations
  • Custom iterators
  • C++20 ranges and iterators
  • Non-modifying sequence operations
  • Modifying sequence operations
  • Sorting and searching
  • Numeric algorithms
  • C++20 ranges algorithms
  • Ranges library
  • Views and adaptors
  • Concepts and constraints
  • std::span, std::mdspan (C++23)
  • New algorithms and utilities
  • std::string and std::string_view
  • std::bitset
  • std::span (C++20)
  • std::optional, std::variant, std::any
  • std::tuple and std::pair

Part II: Advanced C++ Features

  • Function templates
  • Class templates
  • Variadic templates
  • Template specialization
  • SFINAE and Concepts (C++20)
  • Template metaprogramming basics
  • Lambda expressions and captures
  • Generic lambdas (C++14)
  • Template lambdas (C++20)
  • Functional programming patterns
  • Map, filter, reduce
  • Function composition
  • Compile-time computation
  • constexpr and consteval
  • if constexpr (C++17)
  • Type traits
  • SFINAE techniques
  • Advanced metaprogramming
  • Move semantics and perfect forwarding
  • Smart pointers (unique_ptr, shared_ptr, weak_ptr)
  • RAII principles
  • Rule of Five / Rule of Zero
  • Value categories
  • Attributes and inline variables
  • Modern C++ idioms
  • Performance optimization
  • Code organization
  • Error handling
  • Testing and debugging
  • Common anti-patterns to avoid

Part III: Concurrent Programming

  • std::thread and std::jthread (C++20)
  • Mutexes and locks (lock_guard, unique_lock, scoped_lock)
  • Reader-writer locks (shared_mutex)
  • Atomics and memory ordering
  • Condition variables
  • Thread-safe data structures
  • Common concurrency patterns
  • std::async and launch policies
  • std::future and std::promise
  • std::packaged_task and std::shared_future
  • Parallel algorithms (C++17)
  • Thread pools
  • Coroutines (C++20 basics)
  • Best practices for async programming

Part IV: I/O and System Programming

  • Stream I/O (iostream, fstream, sstream)
  • File operations and binary I/O
  • std::filesystem (C++17)
  • Directory iteration and path operations
  • std::format (C++20) and std::print (C++23)
  • Modern string formatting
  • Exception basics and standard exceptions
  • Custom exception classes
  • Exception safety guarantees
  • noexcept specification
  • std::error_code and std::system_error
  • std::expected (C++23)
  • RAII and exception safety
  • Durations and time points
  • Clocks (system_clock, steady_clock)
  • Calendar types (C++20)
  • Timezone support (C++20)
  • Time formatting
  • Performance timing and benchmarking
  • Standard allocators
  • Polymorphic Memory Resources (PMR - C++17)
  • Custom allocators
  • Memory alignment
  • Placement new
  • Object pools and stack allocators
  • Regex syntax and patterns
  • std::regex_match and std::regex_search
  • std::regex_replace and substitution
  • Capture groups
  • Regex iterators
  • Performance considerations
  • Module basics and syntax
  • Module interface and implementation
  • Module partitions
  • Importing standard library
  • Module visibility and encapsulation
  • Migration from headers
  • Coroutine basics (co_await, co_yield, co_return)
  • Generator pattern
  • Async task pattern
  • Promise types and awaitable objects
  • Practical examples (lazy evaluation, pipelines)
  • Performance considerations
  • Best practices and common pitfalls

Key Concepts

Time Complexity Notation

  • O(1) - Constant time
  • O(log n) - Logarithmic time
  • O(n) - Linear time
  • O(n log n) - Linearithmic time
  • O(n²) - Quadratic time

Memory Layout

┌─────────────────────────────────────────┐
│ Stack Memory (automatic storage)        │
│ - Small, fixed-size containers          │
│ - std::array                            │
└─────────────────────────────────────────┘

┌─────────────────────────────────────────┐
│ Heap Memory (dynamic storage)           │
│ - Dynamic containers                    │
│ - std::vector, std::map, etc.           │
│ - Managed via allocators                │
└─────────────────────────────────────────┘

Prerequisites

  • Basic C++ knowledge
  • Understanding of templates
  • Familiarity with pointers and references
  • C++11 or later compiler (C++23 for latest features)

Compiler Support

  • GCC 13+ (full C++23)
  • Clang 16+ (full C++23)
  • MSVC 19.35+ (partial C++23)

How to Use This Tutorial

  1. Start with sequence containers if you're new to STL
  2. Each file contains detailed explanations with ASCII diagrams
  3. Code examples are provided for each concept
  4. Practice exercises at the end of each section
  5. Build up to advanced topics like ranges and views

Quick Start Example

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    // Create a vector (dynamic array)
    std::vector<int> numbers = {5, 2, 8, 1, 9};
    
    // Sort using STL algorithm
    std::sort(numbers.begin(), numbers.end());
    
    // Print using range-based for loop (C++11)
    for (int num : numbers) {
        std::cout << num << " ";
    }
    // Output: 1 2 5 8 9
    
    return 0;
}

STL Philosophy

Generic Programming: Write code once, use with any type

Template Function/Class
        │
        ├─► Works with int
        ├─► Works with double
        ├─► Works with custom types
        └─► Works with any compatible type

Separation of Concerns:

  • Containers know how to store data
  • Iterators know how to traverse data
  • Algorithms know how to process data
  • Each component is independent and reusable

Benefits of STL

  1. Reusability: Don't reinvent the wheel
  2. Efficiency: Highly optimized implementations
  3. Type Safety: Compile-time type checking
  4. Flexibility: Works with any compatible type
  5. Standardization: Portable across platforms
  6. Modern C++: Constantly evolving with new standards

Learning Path

For Beginners

  1. Start with: OOP Concepts - Essential foundation
  2. Then learn: Sequence Containers
  3. Learn Algorithms
  4. Understand Iterators
  5. Explore Utility Containers

For Intermediate Developers

  1. Master Associative and Unordered Containers
  2. Study Modern C++20/23 Features
  3. Learn Lambdas
  4. Understand Templates

For Advanced Users

  1. Deep dive into Metaprogramming
  2. Master Advanced Features
  3. Study Best Practices
  4. Learn Multithreading
  5. Master Async Programming
  6. Learn Coroutines for elegant async code
  7. Explore I/O and Filesystem
  8. Study Exception Handling
  9. Understand Memory Management

Tutorial Contents Summary

Quick Reference (⭐ Bookmark this!)
└── Complete cheat sheet for daily C++ development

Part 0: Foundations (1 chapter)
└── Object-Oriented Programming fundamentals (classes, inheritance, polymorphism)

Part I: STL Fundamentals (8 chapters)
├── Containers (vectors, lists, maps, sets, etc.)
├── Algorithms (sorting, searching, transforming)
├── Iterators (accessing container elements)
└── Modern features (ranges, views, span)

Part II: Advanced C++ (5 chapters)
├── Templates (generic programming foundation)
├── Lambdas (functional programming)
├── Metaprogramming (compile-time computation)
├── Advanced features (move semantics, smart pointers)
└── Best practices (idioms, patterns, optimization)

Part III: Concurrent Programming (2 chapters)
├── Multithreading (threads, mutexes, atomics)
└── Async programming (futures, promises, parallel algorithms)

Part IV: I/O and System Programming (7 chapters)
├── I/O, filesystem, and formatting
├── Exception handling and error management
├── Time and chrono library
├── Memory management and allocators
├── Regular expressions
├── Modules (C++20)
└── Coroutines (C++20)

Total: 23 comprehensive chapters with examples and diagrams

Navigation

🚀 Getting Started

📚 Quick Access


📖 Additional Resources

Condensed cheat sheet for daily development:

  • Container selection decision tree
  • Time complexity table for all containers
  • Most common algorithms with syntax
  • C++11/14/17/20/23 feature lookup
  • Common design patterns
  • Performance tips
  • Complete gotchas checklist
  • Container operations reference
  • Lambda syntax guide
  • Smart pointer reference

Bookmark this page for fast lookup while coding!


Complete tutorial: 23 comprehensive chapters + quick reference guide Covering C++98 through C++23 standard including OOP fundamentals