Utility Libraries

Back

Loading concept...

🧰 C++ Utility Libraries: Your Magical Toolbox

Imagine you have a super-powered toolbox. Inside are special tools that help you with time, random choices, files, numbers, math, and even tiny bits of data. Let’s open it up!


🎯 What’s Inside This Toolbox?

Think of C++ Utility Libraries like a magical helper drawer in your room:

Tool What It Does
⏱️ Chrono Tells time & measures speed
🎲 Random Picks random stuff fairly
πŸ“ Filesystem Organizes your files
πŸ“ Numeric Limits Shows number boundaries
βž— Math Functions Does math for you
πŸ”’ Bit Manipulation Plays with tiny on/off switches

⏱️ Chrono Library: Your Time Machine

What is Chrono?

Imagine you have a super-accurate stopwatch that never lies. That’s the Chrono library! It helps you:

  • Know what time it is
  • Measure how long something takes
  • Wait for a specific amount of time

The Three Time Friends

#include <chrono>
using namespace std::chrono;

// Durations - how long?
seconds sec(5);      // 5 seconds
milliseconds ms(100); // 100 milliseconds

// Time points - when?
auto now = system_clock::now();

// Clocks - the stopwatch
auto start = high_resolution_clock::now();
// ... do stuff ...
auto end = high_resolution_clock::now();
auto time = duration_cast<milliseconds>(
    end - start
);

Real-Life Example: Race Timer

#include <iostream>
#include <chrono>
#include <thread>

int main() {
    using namespace std::chrono;

    auto start = high_resolution_clock::now();

    // Simulate a race (wait 2 seconds)
    std::this_thread::sleep_for(seconds(2));

    auto end = high_resolution_clock::now();
    auto duration = duration_cast<milliseconds>(
        end - start
    );

    std::cout << "Race time: "
              << duration.count()
              << " ms" << std::endl;
    return 0;
}

Three Types of Clocks

graph TD A["πŸ• Clocks"] --> B["system_clock"] A --> C["steady_clock"] A --> D["high_resolution_clock"] B --> E["Real world time"] C --> F["Never goes backward"] D --> G["Most precise timing"]

Remember: Use steady_clock for measuring how long things take. It never jumps around!


🎲 Random Number Generation: Fair Dice Rolling

Why Not Just Use rand()?

The old rand() function is like a broken dice - it’s not really fair. The new <random> library gives you perfectly fair dice!

The Random Recipe

  1. Engine = The dice itself (generates raw numbers)
  2. Distribution = The rules (what numbers you want)
#include <random>
#include <iostream>

int main() {
    // Step 1: Create the engine (dice)
    std::random_device rd;   // True random seed
    std::mt19937 gen(rd());  // Mersenne Twister

    // Step 2: Set the rules
    std::uniform_int_distribution<>
        dice(1, 6);  // 1 to 6

    // Step 3: Roll!
    int roll = dice(gen);
    std::cout << "You rolled: " << roll;
    return 0;
}

Different Types of Random

graph TD A["🎲 Distributions"] --> B["uniform_int"] A --> C["uniform_real"] A --> D["normal"] A --> E["bernoulli"] B --> F["Equal chance: 1-6"] C --> G["Decimals: 0.0-1.0"] D --> H["Bell curve"] E --> I["Yes/No flip"]

Example: Coin Flip

#include <random>
#include <iostream>

int main() {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::bernoulli_distribution coin(0.5);

    if (coin(gen)) {
        std::cout << "Heads!";
    } else {
        std::cout << "Tails!";
    }
    return 0;
}

πŸ“ Filesystem Library: Your File Organizer

What Can It Do?

The Filesystem library is like having a robot assistant that can:

  • Check if files exist
  • Create folders
  • Copy and move files
  • List everything in a folder

Basic Operations

#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;

int main() {
    // Check if file exists
    if (fs::exists("myfile.txt")) {
        std::cout << "File found!";
    }

    // Create a folder
    fs::create_directory("new_folder");

    // Get file size
    auto size = fs::file_size("myfile.txt");
    std::cout << "Size: " << size << " bytes";

    return 0;
}

Path Magic

#include <filesystem>
namespace fs = std::filesystem;

int main() {
    fs::path p = "/home/user/docs/file.txt";

    // Break it apart
    p.parent_path();  // /home/user/docs
    p.filename();     // file.txt
    p.extension();    // .txt
    p.stem();         // file

    // Build paths safely
    fs::path folder = "/home/user";
    fs::path file = folder / "docs" / "file.txt";
    // Result: /home/user/docs/file.txt

    return 0;
}

List All Files in a Folder

#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;

int main() {
    for (auto& entry :
         fs::directory_iterator("my_folder")) {
        std::cout << entry.path() << "\n";
    }
    return 0;
}

πŸ“ Numeric Limits: Number Boundaries

What Are Limits?

Every number type has boundaries - like how a cup can only hold so much water. numeric_limits tells you these boundaries!

graph TD A["πŸ“ Numeric Limits"] --> B["min - smallest"] A --> C["max - largest"] A --> D["digits - bit count"] A --> E["is_signed - has negatives?"]

Finding the Edges

#include <limits>
#include <iostream>

int main() {
    using namespace std;

    // Integer limits
    cout << "int max: "
         << numeric_limits<int>::max()
         << "\n";
    // Output: 2147483647

    cout << "int min: "
         << numeric_limits<int>::min()
         << "\n";
    // Output: -2147483648

    // Float limits
    cout << "float max: "
         << numeric_limits<float>::max()
         << "\n";

    return 0;
}

Common Limits Table

Type Min Max
char -128 127
int -2,147,483,648 2,147,483,647
unsigned int 0 4,294,967,295
long long -9 quintillion 9 quintillion

Special Values

#include <limits>
#include <iostream>

int main() {
    using lim = std::numeric_limits<double>;

    // Infinity!
    double inf = lim::infinity();

    // Smallest positive number
    double tiny = lim::epsilon();

    // Is it a number with decimals?
    bool hasDecimals = lim::is_integer;

    return 0;
}

βž— Mathematical Functions: Your Math Helper

Basic Math (from <cmath>)

#include <cmath>
#include <iostream>

int main() {
    // Absolute value (remove negative)
    std::abs(-5);    // 5

    // Power (2 to the power of 3)
    std::pow(2, 3);  // 8

    // Square root
    std::sqrt(16);   // 4

    // Round numbers
    std::round(3.7); // 4
    std::floor(3.7); // 3 (round down)
    std::ceil(3.2);  // 4 (round up)

    return 0;
}

Trigonometry (Circle Math)

#include <cmath>

int main() {
    double angle = 3.14159 / 4; // 45 degrees

    std::sin(angle);  // Sine
    std::cos(angle);  // Cosine
    std::tan(angle);  // Tangent

    // Convert degrees to radians
    double deg = 90;
    double rad = deg * 3.14159 / 180;

    return 0;
}

Logarithms (Reverse of Powers)

#include <cmath>
#include <iostream>

int main() {
    // Natural log (base e)
    std::log(2.71828);  // ~1

    // Log base 10
    std::log10(100);    // 2

    // Log base 2
    std::log2(8);       // 3

    // Exponential (e^x)
    std::exp(1);        // 2.71828...

    return 0;
}

Math Function Map

graph TD A["βž— Math Functions"] --> B["Basic"] A --> C["Trig"] A --> D["Logarithm"] A --> E["Special"] B --> F["abs, pow, sqrt"] C --> G["sin, cos, tan"] D --> H["log, log10, log2"] E --> I["round, floor, ceil"]

πŸ”’ Bit Manipulation: Playing with Switches

What Are Bits?

Imagine a row of light switches. Each switch is either ON (1) or OFF (0). That’s what bits are! A byte is 8 switches together.

Number 5 = 00000101
           ↑↑↑↑↑↑↑↑
           8 switches (bits)

Basic Bit Operations

#include <iostream>

int main() {
    int a = 5;  // 0101 in binary
    int b = 3;  // 0011 in binary

    // AND: both must be ON
    int c = a & b;  // 0001 = 1

    // OR: either can be ON
    int d = a | b;  // 0111 = 7

    // XOR: only one can be ON
    int e = a ^ b;  // 0110 = 6

    // NOT: flip all switches
    int f = ~a;     // 1111...1010

    return 0;
}

Shifting Bits

#include <iostream>

int main() {
    int x = 4;  // 0100 in binary

    // Shift left (multiply by 2)
    int left = x << 1;  // 1000 = 8

    // Shift right (divide by 2)
    int right = x >> 1; // 0010 = 2

    return 0;
}

C++20 Bit Functions (from <bit>)

#include <bit>
#include <iostream>

int main() {
    unsigned int n = 12; // 1100 in binary

    // Count ON switches
    int ones = std::popcount(n);  // 2

    // Count leading zeros
    int lead = std::countl_zero(n);

    // Check if power of 2
    bool isPow2 = std::has_single_bit(n);

    // Rotate bits
    auto rotated = std::rotl(n, 2);

    return 0;
}

Bit Operations Visual

graph TD A["πŸ”’ Bit Operations"] --> B["Logical"] A --> C["Shift"] A --> D["C++20"] B --> E["AND &amp;&lt;br&gt;OR &#124;&lt;br&gt;XOR ^&lt;br&gt;NOT ~"] C --> F["Left &lt;&lt; &lt;br&gt;Right &gt;&gt;"] D --> G["popcount&lt;br&gt;countl_zero&lt;br&gt;has_single_bit"]

Common Bit Tricks

#include <iostream>

int main() {
    int n = 10;

    // Check if even
    bool isEven = (n & 1) == 0;

    // Multiply by 2
    int doubled = n << 1;

    // Divide by 2
    int halved = n >> 1;

    // Toggle a specific bit
    int bit = 2; // third bit (0-indexed)
    n = n ^ (1 << bit);

    return 0;
}

🎁 Quick Reference Summary

Library Include Purpose
Chrono <chrono> Time & duration
Random <random> Fair random numbers
Filesystem <filesystem> File operations
Limits <limits> Number boundaries
Math <cmath> Math functions
Bit <bit> Bit manipulation

πŸš€ You Did It!

You’ve explored the C++ Utility Toolbox! Now you know:

  • ⏱️ How to measure time with Chrono
  • 🎲 How to generate fair random numbers
  • πŸ“ How to work with files and folders
  • πŸ“ Where numbers begin and end
  • βž— How to do math the easy way
  • πŸ”’ How to play with individual bits

These tools are like superpowers. Use them wisely, and your programs will be faster, smarter, and more reliable!


Remember: Every expert was once a beginner. Keep practicing, and these tools will become second nature! 🌟

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.