Skip to main content

Posts

Showing posts with the label Cplusplus

std::expected vs Exceptions for CLI Tools

If you've ever written a command-line tool in C++, you've hit this moment: a file won't open, a flag is malformed, a config value is garbage — and now what? Do you throw ? Do you return some sentinel value and hope everyone remembers to check it? C++23 gave us a new option, std::expected , and it's changed how a lot of people answer that question. This article walks through both approaches, explains the tradeoffs in plain English, and shows real code so you can decide for yourself. The Core Idea, In One Sentence Exceptions say "something went wrong, stop everything, and let some code way up the call stack deal with it." std::expected says "this function might fail, so its return type honestly says so — you can't ignore it without looking silly." That's really the whole philosophical difference. Everything else is details. A Mental Model: The Post Office vs. The Vending Machine Think of exceptions like mailing a letter. You drop it in...

std::expected: Error Handling in C++23

 The Problem We're Actually Solving Let's start before the code. Imagine you write a function that divides two numbers. Easy, right? Except... what happens if someone tries to divide by zero? Your function needs a way to say "hey, something went wrong here" without crashing the whole program or lying about the result. For decades, C++ programmers have had a few messy options: Throw an exception — works, but exceptions are expensive, and some codebases (game engines, embedded systems) avoid them entirely. Return an error code — cheap, but easy to ignore. Nobody checks return codes reliably, and you lose the "why" behind the failure. Use an output parameter — pass a pointer or reference to fill in with an error. Clunky and easy to mess up. Return a std::optional — tells you something failed, but not what or why . C++23 gives us a much cleaner tool: std::expected . Think of it as a box that either contains your successful result, or contains the ...

C++ Conan + CMake Presets

 If you've ever tried to build a C++ project and thought "why is this so much harder than every other language," you're not crazy. C++ doesn't come with a built-in way to grab libraries or remember your build settings. Two tools fix that: Conan (fetches libraries) and CMake Presets (remembers your settings). Let's build something real together. First, What Even Are These Two Things? Think of building a C++ project like cooking a meal. Conan is your grocery delivery service. You tell it "I need fmt, I need Boost, I need zlib" and it shows up with those ingredients already prepped, instead of you driving to five different stores. CMake is your recipe/instructions for actually cooking (compiling) the meal (your program). CMake Presets are like saving your favorite recipe settings — "always preheat to 375, always use the big pot" — so you don't have to type the same long commands every single time. Put together: Conan gets your...

C++ vcpkg Manifest Mode + CMake

 If you've ever tried to install a C++ library and felt like you were assembling furniture without instructions, this article is for you. We're going to talk about vcpkg manifest mode and how it works with CMake , and I'm going to explain it like you're five years old (in a good way — no judgment here). First, Let's Talk About the Problem In most programming languages, adding a library is easy. Python has pip install requests . JavaScript has npm install express . You type one command, and boom, the library shows up in your project. C++ never really had that. For decades, if you wanted to use a library like fmt or nlohmann/json , you had to: Download the source code yourself Figure out how to compile it Tell your compiler where to find the headers Tell your linker where to find the compiled binaries Cry a little vcpkg is Microsoft's answer to this mess. It's a package manager for C++ — like pip or npm , but for C++ libraries. And manifest mode...

Cplusplus Iterators

C++ is a robust programming language, offering flexibility to handle data efficiently. Among its many features, iterators stand out as an essential part of working with containers like vectors, lists, and maps. But what exactly is an iterator, and why should you care? In this article, we’ll break it all down, using plain language and helpful examples along the way. What Is an Iterator in C++? An iterator is like a pointer that allows you to traverse through the elements of a container (such as an array or a list). Think of it as a bookmark that tells you where you are in a collection of data and lets you move to the next or previous element. Iterators form the backbone of the Standard Template Library (STL) in C++, making it easier to manipulate containers without worrying about their underlying details. With iterators, you can: Access elements in a sequence. Navigate through a container. Modify or process elements directly. Types of Iterators C++ provides several types of...

Cplusplus Maps

Have you ever wondered how you can associate one piece of data with another in C++? Maybe you need to store a student’s name and their corresponding grades, or link product IDs to their prices. Enter C++ maps , a powerful feature in the Standard Template Library (STL) that provides an easy way to work with key-value pairs. In this article, you’ll learn what C++ maps are, how they work, and how to use them effectively. By the end, you’ll feel confident enough to start using maps in your C++ projects. What Are C++ Maps? Simply put, a map in C++ is a container that stores elements as key-value pairs . Each key is unique, making it easy to retrieve the associated value quickly. Think of it like a real-world dictionary: you look up a word (the key), and the dictionary provides a definition (the value). C++ maps are implemented as balanced binary search trees, which means keys are always stored in sorted order . This sorting is handled automatically, so you don’t need to worry about org...

Cplusplus Sets

C++ sets can seem intimidating at first, but they are powerful tools for organizing data. In simplest terms, a set is a collection of unique elements. If you've ever felt frustrated managing duplicates in your program, sets can solve that problem for you. In this article, I'll guide you through the essentials of C++ sets. We’ll cover how they work, common use cases, and see examples of their implementation. What Is a Set in C++? A set is a part of C++'s Standard Template Library (STL). Think of it like a container that automatically ensures all its elements are unique. Unlike arrays or vectors, sets don’t allow duplicates. If you try adding an element that already exists, it simply won’t be added. Additionally, sets store their elements in sorted order. This means you don’t need to manually sort the data—it's handled for you. Sets are especially handy if you need fast lookups, insertions, or deletions. They work behind the scenes using something called a binary se...

Cplusplus Deque

If you’re working with C++, you’ve likely come across a container called a deque. Short for “double-ended queue,” the deque is a versatile data structure. It allows fast insertion and deletion at both ends, making it a great choice for certain types of algorithms. In this article, we’ll break down what C++ deques are, how they work, and when to use them. We’ll also include practical code examples to show how you can make the most of this container. What Is a Deque in C++? A deque is similar to a vector, another popular container in C++. But while a vector allows fast access and modification primarily at the back, a deque offers more flexibility. It’s designed for efficient addition and removal at both the front and back. Deques use a complex internal structure that organizes elements in blocks, ensuring fast operations at either end without compromising performance. Key Features of a Deque When deciding whether to use a deque, consider these features: Dynamic Size : A deque c...

C++ Stacks

Stacks are a fundamental data structure in programming, and C++ makes working with them straightforward and efficient. Whether you're new to programming or just brushing up on your skills, stacks are a concept you’ll encounter in many applications. Let’s break it all down step by step. What Is a Stack? At its core, a stack is a collection of elements organized in a Last In, First Out (LIFO) order. This means the last item added to the stack is the first one to be removed. Think of a stack as a pile of plates—you add plates on top and take them off from the top. It’s that simple. Stacks are used everywhere in computing, from managing function calls in recursion to evaluating mathematical expressions. In C++, stacks are available as part of the Standard Template Library (STL), making them versatile and easy to use. Why Use Stacks? Stacks are particularly handy when you need to manage tasks in a specific sequence. Here are some key use cases: Undo functionality in text editors...

Cplusplus Lists: A Comprehensive Guide

C++ is one of the most powerful programming languages, offering developers a range of data structures to handle complex tasks. Among these, the list stands out as a versatile option for managing collections of data. But what exactly is a list in C++? How does it work, and why should you consider using one in your program? Let’s break it down. What Is a C++ List? In C++, a list is an implementation of a doubly linked list provided by the Standard Template Library (STL). Unlike arrays or vectors, which store elements in contiguous memory locations, a list consists of nodes. Each node contains an element and pointers to the next and previous nodes. The doubly linked nature of a list makes it ideal for certain operations like frequent insertions or deletions at any position. If you’re dealing with dynamic data, where items might be added or removed often, a list can help improve performance. Why Use a C++ List? When should you choose a list over other data structures like a vect...

Cplusplus Vectors

Vectors are a cornerstone of modern C++ programming. If you’re working on dynamic arrays or need a versatile data structure, vectors are one of the best tools in your toolkit. Unlike traditional arrays, they can adjust their size automatically. This flexibility, combined with a host of built-in functions, makes them a popular choice among developers. Let’s explore how vectors work, common use cases, and some practical examples to help you get started. What Are Vectors in C++? Vectors in C++ are part of the Standard Template Library (STL). They’re dynamic arrays that grow or shrink as needed. While built-in arrays have a fixed size, vectors handle memory allocation and resizing for you. This makes them incredibly convenient for scenarios where the size of your data isn’t known upfront. Think of vectors as a more intelligent version of arrays. They not only hold multiple elements of the same type but also offer functionalities like adding, removing, or accessing elements without manu...

Cplusplus Data Structures

C++ is one of the most commonly used programming languages, particularly in fields like game development, embedded systems, and high-performance computing. One reason for its popularity lies in its ability to manipulate data through a variety of data structures. Understanding these data structures is essential for writing efficient code that solves real-world problems. But what are data structures, and why should you care? Think of them as specialized containers used to organize data in ways that allow for efficient access, modification, or storage. Let’s explore the most commonly used data structures in C++ and see how they work through simple examples. What Are Data Structures in C++? Put simply, a data structure is a format for storing and organizing data. Different structures serve different purposes, and the right one can save time and computational resources. C++ offers both built-in data structures, like arrays, and advanced data structures through the Standard Template Libr...

Cplusplus Date and Time

Managing dates and times in C++ can seem complex at first, but with the right tools and understanding, it becomes much simpler. Whether you're building a scheduling app or logging events, knowing how to work with time efficiently matters. In this guide, we'll break down date and time handling in C++ with clear explanations and practical examples. Why Work with Date and Time in C++? Time-related operations aren't just for clocks or calendars. From calculating differences between events to formatting data for logs, a solid grasp of time handling is essential. C++ offers several built-in libraries to work with time seamlessly, including <ctime> , <chrono> , and <iomanip> . Getting Started: The <ctime> Library The <ctime> library is one of the oldest solutions to handle time in C++. It provides basic support for dealing with system time and formatting it. Example: Displaying the Current Time #include <iostream> #include <ctime> ...