<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Atharv Rawat on Medium]]></title>
        <description><![CDATA[Stories by Atharv Rawat on Medium]]></description>
        <link>https://medium.com/@atharvesting?source=rss-a2c7b71eea75------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dQsOL0NAKYDKKeLiurO5jg.png</url>
            <title>Stories by Atharv Rawat on Medium</title>
            <link>https://medium.com/@atharvesting?source=rss-a2c7b71eea75------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:49:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@atharvesting/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Threadpooling in Stochastic Gradient Descent]]></title>
            <link>https://atharvesting.medium.com/threadpooling-in-stochastic-gradient-descent-1fa93e1e6c65?source=rss-a2c7b71eea75------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fa93e1e6c65</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[thread-pool]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <dc:creator><![CDATA[Atharv Rawat]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 19:08:26 GMT</pubDate>
            <atom:updated>2026-08-19T19:11:40.822Z</atom:updated>
            <content:encoded><![CDATA[<p>If you haven’t read my previous blog <a href="https://atharvesting.medium.com/multithreads-of-madness-2a66bc8c0cde">Multithreads of Madness</a>, you probably should, because you’ll get a chance to witness some real tragic comedy. Undoubtedly, at my generous expense.</p><p>If you already feel hooked to this one (i totally understand), the TLDR is that my multithreaded matrix multiplication function spawned a bunch of threads <em>every time</em> the function was called for a sufficiently big matrix. And for doing deep learning work, if that is not a clear death sentence, I don’t know what is.</p><p>In hindsight, that explains why that blog performed so poorly lol.</p><p>The blog wasn’t entirely rubbish though. It intuitively introduced multi-threading, went over major trade-offs (ironic) and had a killer icebreaker joke.</p><p>While the multiplication function clearly demonstrated desirable results, the problem was that it was isolated. In a way that it could only serve as a standalone demo for basic multithreading. If I wanted to implement it for a performance-focused project, it would become critical to implement multithreading as efficiently as possible.</p><p>I have been working on my C++ MNIST Neural Network for a while, and since the SGD training process presented clear opportunities to be parallelized, I was determined to get it right this time.</p><p>Note: This blog assumes basic knowledge of neural networks and backpropagation. However, the thread pool implementation is generally applicable. Its code is sourced from an <a href="https://stackoverflow.com/a/32593825">SO answer</a> and is slightly modified <a href="https://github.com/atharvesting/nnfs-extreme/blob/main/NNFS_Extreme/utils.hpp">for my use case.</a> Keep in mind that this implementation doesn’t support the necessary sophistication required by production systems (like exception handling and graceful shutdowns), nor is it intended to.</p><p>In my C++ neural network (which is heavily inspired by <a href="http://neuralnetworksanddeeplearning.com/">Nielsen’s</a>), the Stochastic Gradient Descent (SGD) algorithm looks roughly as follows -</p><p>For each epoch:</p><ol><li>Shuffle the training data</li><li>Create mini-batches</li><li>Perform backpropagation</li><li>Update parameters</li></ol><p>In terms of the functions in the program, here is the execution flow:</p><ol><li>void SGD(...) calls...</li><li>void update_mini_batch(...) calls...</li><li>void backprop(...)</li></ol><p>At first, I was running the pipeline serially. A single thread was going through each epoch one after another, one mini-batch after another and one training sample after another.</p><p>In order to expedite the training process, I naturally leaned towards implementing concurrency. The first question I asked was — Can I parallelize epochs?</p><p>I am using a synchronous SGD implementation, where each epoch begins from the parameters produced by the previous epoch, meaning that parallelizing epochs would be impossible. Here is a simple justification: Imagine a multi-dimensional parameter hyperplane. Just kidding. Instead, imagine the hilly land with multiple peaks and valleys. This landscape represents the loss function. We want to get to the lowest point in this landscape, as this position has the minimum loss.</p><p>Gradient descent works by finding the gradient and direction of steepest ascent given a reference point and descending in the opposite direction by a certain amount. If I am on point A, and I find the steepest direction and move downwards. But at the new point B, it is highly unnecessary that the next direction of descent will be the same. Which implies the following — I need my current location to descend to the next point and I am at my current location because of where I was before.</p><figure><img alt="A simplified visualization of the gradient descent optimization algorithm" src="https://cdn-images-1.medium.com/max/797/1*Dqrm88Dz38rsbf6TzcpHyA.png" /><figcaption>looks like a fun ride :)</figcaption></figure><p>In each epoch, I am essentially judging my current location to decide where to move next. That is a clear sequential task.</p><p>It is a different story when go a level deeper. Common implementations of update_mini_batch() take the container full of batches of training samples and apply backpropagation to each batch. The accumulated gradients are then subtracted from the current parameters (or coordinates if the hill analogy resonated with you).</p><p>Now, it is the same thing if we calculate the loss function for the entire training data set or calculate the function for n batches and add them up. Since the derivative of sums is equal to the sum of derivatives, the gradient of the loss function for the entire dataset can be represented by the sum of gradients of the loss function for each batch.</p><p>In standard mini-batch SGD, the parameters (weights and biases) are updated after processing each mini-batch. Just like the sequential nature of epochs, the mini-batches must also be executed sequentially to ensure the integrity of each step “downwards”.</p><p>(<a href="https://arxiv.org/abs/2501.16168">Asynchronous SGD</a> does exist, but it introduces optimisation problems that simply aren’t worth it for simple networks like the one discussed here. For this reason, we will take sequentiality for granted in this blog.)</p><p>Going a level deeper, notice that the parameters are updated only after processing an entire mini-batch. Therefore, the individual training samples within that mini-batch can be processed concurrently, as long as each worker computes its gradient contribution independently and the contributions are aggregated before the parameter update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dtlo-wldzHWgoNTo-6ssA.png" /><figcaption>how original. ik.</figcaption></figure><p>Here is the ThreadPool class declaration:</p><pre>class ThreadPool {<br>public:<br>    ~ThreadPool();<br>    void Start();<br>    void QueueJob(const std::function&lt;void()&gt;&amp; job);<br>    void QueueBatch(const std::vector&lt;std::function&lt;void()&gt;&gt;&amp; job_batch);<br>    void Wait();<br>    void Stop();<br>    bool busy();<br>private:<br>    bool should_terminate = false;<br>    size_t pending_tasks = 0;<br>    std::mutex queue_mutex;<br>    std::condition_variable mutex_condition;<br>    std::condition_variable wait_condition;<br>    std::vector&lt;std::thread&gt; threads;<br>    std::queue&lt;std::function&lt;void()&gt;&gt; jobs;<br>    <br>    void ThreadLoop();<br>};</pre><p>Let’s go through each member function:</p><pre>void ThreadPool::Start() {<br>    const int num_threads = std::thread::hardware_concurrency();<br>    threads.reserve(num_threads);<br>    <br>    for (int i  = 0; i &lt; num_threads; i++) <br>    {<br>        threads.emplace_back(&amp;ThreadPool::ThreadLoop, this);<br>    }<br>}</pre><p>std::thread::hardware_concurrency() gives us a rough idea about the number of hardware threads that can execute concurrently. (hardware_concurrency() can return 0 when the implementation cannot determine the value, so production code should provide a fallback.) Capacity for the corresponding number of std::thread objects is reserved in the vector. Each call to emplace_back() then constructs a new thread whose entry point is ThreadLoop(this).</p><pre>void ThreadPool::ThreadLoop() {<br>    while (true) {<br>        std::function&lt;void()&gt; job;<br>        <br>        {<br>            std::unique_lock&lt;std::mutex&gt; lock(queue_mutex);<br>            mutex_condition.wait(lock, [this] {<br>                return !jobs.empty() || should_terminate;<br>            });<br>            if (should_terminate) {<br>                return;<br>            }<br>            job = jobs.front();<br>            jobs.pop();<br>        }<br>        <br>        job();<br><br>        {<br>            std::unique_lock&lt;std::mutex&gt; lock(queue_mutex);<br>            pending_tasks--;<br>            if (pending_tasks == 0) {<br>                wait_condition.notify_all();<br>            }<br>        }<br>    }<br>}</pre><p>Each thread executes the same continuous loop until the thread pool is stopped. A function object job is initialized.</p><p>The braces might seem random and even unnecessary, but they serve a vital purpose that stems from one of the most fundamental language features. Each set of braces creates its own scope. All variables initialized within a set of braces will only exist within them. Leaving the braces results in them getting out of scope and being destructed.</p><p>Continuing with ThreadLoop, we can see braces being used to set a local scope. This is a common pattern applied when using RAII mutex guards like std::lock_guard, and std::unique_lock, as it allows the guard to automatically unlock the mutex when it goes out of scope. In other words, the braces limit the lifetime of the lock guard so that the mutex is automatically released at the desired point. RAII for life! Notice that we wanted the guard to only be active for a particular section of the function, namely where we access the shared jobs queue to take a task.</p><p>mutex_condition.wait() blocks the thread until either (1) the jobs queue is non-empty or (2) the signal to terminate the pool has been sent out. It does so by releasing the mutex and putting the thread to sleep. When the condition variable is notified (or a <a href="https://en.wikipedia.org/wiki/Spurious_wakeup">spurious wakeup</a> occurs), the thread reacquires the mutex and evaluates the predicate again. Using std::condition_variable avoids the unnecessary CPU consumption of active polling.</p><p>When the predicate evaluates to true, the worker copies the job out of the queue, leaves the scope, and releases queue_mutex <strong>before executing the job</strong>. It is important to understand that a thread will only get to this point when it actually has received a job. Until then, the thread will essentially be suspended by wait().</p><p>After the job is finished, we create another local scope where the pending_tasks shared counter is decremented. pending_tasks counts every submitted task that has not yet completed—meaning it includes both tasks waiting in jobs and tasks currently being executed by workers. Finally, if there are no remaining tasks (pending_tasks == 0), we notify all threads waiting on wait_condition.</p><pre>void ThreadPool::QueueJob(const std::function&lt;void()&gt;&amp; job) {<br>    {<br>        std::unique_lock&lt;std::mutex&gt; lock(queue_mutex);<br>        jobs.push(job);<br>        pending_tasks++;<br>    }<br>    mutex_condition.notify_one();<br>}</pre><p>Again, the local scope exists to control the lifetime of lock. We acquire the mutex lock, push the new function to jobs, and increment pending_tasks. The mutex is released automatically when the scope ends.</p><p>When a new task is enqueued, only one waiting thread is notified via notify_one() to wake up and take the task.</p><pre>void ThreadPool::QueueBatch(const std::vector&lt;std::function&lt;void()&gt;&gt;&amp; job_batch) {<br>    if (job_batch.empty()) return;<br>    {<br>        std::unique_lock&lt;std::mutex&gt; lock(queue_mutex);<br>        for (const auto&amp; job : job_batch) {<br>            jobs.push(job);<br>        }<br>        pending_tasks += job_batch.size();<br>    }<br>    mutex_condition.notify_all();<br>}</pre><p>This is simply a batched version of ThreadPool::QueueJob. The only relevant difference is that instead of notifying a single thread, we call notify_all() so that all waiting threads are notified.</p><p>The way this works: Threads are woken from sleep when notify_all() is called. They land back on to the wait() function from ThreadLoop, where they need to wait their turn to access the mutex. Once it is acquired, they check whether they can take up a task via the predicate. If yes, then they get on with that task. If the predicate still isn&#39;t fulfilled, then they go back to sleep and give up the mutex for another thread to try.</p><pre>bool ThreadPool::busy() {<br>    std::unique_lock&lt;std::mutex&gt; lock(queue_mutex);<br>    return pending_tasks &gt; 0;<br>}</pre><p>Simply put, if any thread is still executing its task(s), or the jobs shared queue is non-empty, busy() will return true. Otherwise false. pending_tasks counts both currently executing tasks as well as tasks inside the shared queue.</p><pre>void ThreadPool::Wait() {<br>    std::unique_lock&lt;std::mutex&gt; lock(queue_mutex);<br>    wait_condition.wait(lock, [this] { return pending_tasks == 0; });<br>}</pre><p>Naturally, we need a way to ensure that ThreadPool finishes all of the assigned tasks before a certain point. This is similar to using std::thread::join() (see <a href="https://medium.com/@atharvesting/multithreads-of-madness-2a66bc8c0cde?sharedUserId=atharvesting">Multithreads of Madness</a> for how that works), except that we need to actually keep the threads alive to execute future tasks.</p><p>This works by acquiring the mutex and checking the predicate. If pending_tasks &gt; 0, the mutex is released and the calling thread (in this case, the main thread) is suspended. When a worker finishes a job, it acquires the mutex, decrements pending_tasks, and calls wait_condition.notify_all(). Wait() wakes up, reacquires the mutex, and re-evaluates the predicate. Once pending_tasks == 0, Wait() returns and the calling thread can continue execution.</p><p>Note that this function doesn’t prevent other threads from enqueuing tasks. It works under the assumption that no further tasks will be added after Wait() is called.</p><p>Initially, I implemented this function as follows:</p><pre>void ThreadPool::Wait() {<br>	while (busy());<br>}</pre><p>A simple and intuitive polling loop that actually has a deep resource cost. Not only is the mutex constantly acquired and released when busy() is called, but the active polling also overloads the CPU and wastes resources.</p><pre>void ThreadPool::Stop() {<br>    {<br>        std::unique_lock&lt;std::mutex&gt; lock(queue_mutex);<br>        should_terminate = true;<br>    }<br>    mutex_condition.notify_all();<br>    for (std::thread&amp; active_thread : threads) {<br>        active_thread.join();<br>    }<br>    threads.clear();<br>}</pre><p>To stop the pool, we acquire queue_mutex within a local scope, set the shared flag should_terminate = true, and release the lock. We then call mutex_condition.notify_all() so all waiting threads wake up and check their predicate.</p><p>It is important to understand the shutdown semantics here: Stop() prevents workers from taking additional queued jobs. Workers that are already executing a job will finish it before checking should_terminate at the top of the loop and exiting. However, workers that are currently waiting will wake up, observe should_terminate == true, and immediately return—meaning any unstarted tasks remaining in jobs may be abandoned. For this reason, it is essential to call Wait() before Stop() if you want all enqueued tasks to complete.</p><p><strong>Rule of thumb:</strong> when shared state changes in a way that could make a waiting predicate true, notify the corresponding condition variable.</p><p>References:</p><ul><li><a href="https://en.cppreference.com/cpp/thread/condition_variable">std::condition_variable</a></li><li><a href="https://medium.com/@litombeg/concurrency-in-c-conditional-variables-9c688298c4b9">Concurrency in C++ : Conditional Variables</a></li></ul><p>Deep Learning for Electrophysiological Investigation and Estimation of Anesthetic-Induced Unconsciousness — Scientific Figure on ResearchGate. Available from: <a href="https://www.researchgate.net/figure/Gradient-descent-visualization-Amini-et-al-2018-At-each-training-step-epoch-the_fig9_364197638">https://www.researchgate.net/figure/Gradient-descent-visualization-Amini-et-al-2018-At-each-training-step-epoch-the_fig9_364197638</a> [accessed 17 Aug 2026]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fa93e1e6c65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreads of Madness]]></title>
            <link>https://atharvesting.medium.com/multithreads-of-madness-2a66bc8c0cde?source=rss-a2c7b71eea75------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a66bc8c0cde</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[hpc]]></category>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Atharv Rawat]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 18:41:56 GMT</pubDate>
            <atom:updated>2026-07-21T17:31:55.050Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reading this blog will become a core memory…</h4><p><em>Laugh at your own risk:</em> A couple of threads walk into a bar, order some drinks, and have a great time. Later, they realize that they have run out of cache and won’t be able to remember this core memory.</p><p>I have been building my very own linear algebra library for the past few weeks. At first, no effort was initially made to make the operations performant, just that they did what they were supposed to. After finishing the initial version ( -(tests + documentation + a few functions) ), I was ready to dip my toes into optimizing the functions.</p><p>Before I get into that, I must confess that I have been so stressed out about my time management lately, that I have started binge watching C++ tutorials while I eat my meals. However bad that sounds, it’s probably worse. This gluttonous consumption did have a silver lining — I learnt about multithreading in C++ (it’s about time honestly).</p><p><a href="https://www.youtube.com/@NotesByNick">Nick aka CoffeeBeforeArch</a> is my favourite programming educator on YouTube. He only teaches C++, and the way he does it makes C++ seem like a language simpler than the girthy Python itself. From him I first learnt about std::thread, and it will be my honour to pass on his knowledge to you from the perspective of the challenges I overcame using it.</p><p>For executing a basic program, certain resources are assigned. To be particular, a thread. A hardware thread (HT from now) is a small part of the CPU core (there are typically 2 threads per core) that can be assigned tasks to execute while leaving the rest of the CPU resources (the other threads) free for other tasks. Now, depending on the system, these resources can generally be in high demand (consistently high CPU usage), or be left idle for most of the time. Somehow there is no in between. My situation fell on the latter end of the spectrum.</p><p>The threads can be thought of as workers. Initially, I had been writing programs (including this library) that was just using a single worker to execute tasks. Nick taught me that we can intentionally harness the power of the extra threads available to us to divide the work between these “workers”.</p><p>That is literally all multithreading is about.</p><p>If you have heard of intimidating terms like parallelization and high-performance computing (HPC), this is literally that. Divide the task between many workers that execute simultaneously.</p><p>Coming to std::thread, that is how C++ is able to spawn OS threads (OST from now). OSTs bridge the gap between hardware threads and software. They are a resource which needs its own stack memory, scheduling priorities among other stuff. The operating system is responsible for distributing OSTs among the available HTs. This means that there can be more OSTs than HTs, in which case the OS must use time-slicing to allocate hardware fairly among all OSTs. Later, you will see why crossing the hardware limit isn&#39;t always the right option.</p><p>The way std::thread works is very simple. It takes 1 + n arguments - a callable, and then the callable&#39;s arguments. An OST is then allocated which executes the callable separately from the main thread (which is responsible for the overall main program).</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br>int main() {<br>    int r1{ 0 }, r2{ 1 };<br>    auto func = [](int&amp; accumulator) {<br>        for (int i = 0; i &lt; 1000; i++) {<br>            accumulator += i;<br>        }<br>    };<br>    std::thread t1(func, std::ref(r1));<br>    std::thread t2(func, std::ref(r2));<br>    t1.join(); t2.join();<br>    <br>    std::cout &lt;&lt; &quot;r1 = &quot; &lt;&lt; r1 &lt;&lt; &quot;\n&quot;;<br>    std::cout &lt;&lt; &quot;r2 = &quot; &lt;&lt; r2 &lt;&lt; &quot;\n&quot;;<br>    <br>    int total = r1 + r2;<br>    std::cout &lt;&lt; &quot;total = &quot; &lt;&lt; total &lt;&lt; std::endl;<br>    <br>    return 0;<br>}</pre><pre>r1 = 499500<br>r2 = 499501  // r2 was initialized to 1!!<br>total = 999001</pre><p>Let’s go through this example:</p><ul><li>I initialize r1 and r2, the two objects to be modified.</li><li>func is a pretty straightforward lambda. The sum of all whole numbers in the range [0, 999] is added to the accumulator. Notice that the accumulator is passed by reference, so the changes naturally reflect in the outer scope.</li><li>The two threads are initialized with the function name, r1, and r2 are passed in the thread constructor. These threads begin executing their instructions immediately upon initialization.</li><li>There is a real reason why r1 and r2 are wrapped in std::ref(). I learnt about this while practicing using std::thread. Unlike normal functions where arguments are automatically passed as references if defined accordingly, std::threads copy lvalues like r1 and r2 to have safe-to-use copies. This circumvents situations where the lvalues go out of scope before the thread actually starts executing. This makes it necessary to explicitly wrap them in std::ref() to force them to be processed as references.</li><li>The thing about using std::thread is that while it executes tasks on the side, the primary program thread continues executing what is next. Which is why situations can arise where the main thread reaches the end of the program before a thread is done with its task.</li><li>In order to avoid this, waiting for the threads to complete their execution is necessary. Setting up this waiting point at the latest possible point in the program (before the results are actually needed) is best for performance, so that the main program mustn’t wait prematurely. For this we use t1.join() and t2.join(), which basically tells the main thread to wait for the parallel threads and their results, which will effectively &quot;join&quot; them back to the main thread.</li></ul><p>Just to hammer down the value proposition of multi-threaded execution, here is what would happen in a sequential, non-multithreaded program — The two loops will be executed one after the other, taking almost double the time that is taken by the multithreaded version. I underlined ‘almost’ because it is doing a lot of heavy lifting here. More on performance later.</p><p>Whew, we can finally end this detour and focus on the problem initially posed. Matrix multiplication is a fundamental operation for any linear algebra library. So getting it as fast as possible is a matter of priority, especially as matrices scale to 1000s of dimensions when solving real deep learning problems. LLMs run on NNs. And NNs are nothing without matrix multiplication.</p><p>The interesting thing is that I use the exact naive approach almost everyone first learns:</p><pre>A (n x m) * B (m x p) = C (n x p)<br><br>for row_idx from 1 to n<br>    for col_idx from 1 to p<br>        sum &lt;- 0<br>        for inner_idx from 1 to m<br>            sum &lt;- sum + A[row_idx][inner_idx] * B[inner_idx][col_idx]<br>        C[row_idx][col_idx] &lt;- sum</pre><p>Here was my first attempt at the multithreaded algorithm:</p><pre>// This function is part of the Matrix class template<br>template &lt;typename T&gt;<br>Matrix&lt;T&gt; fast_mult(const Matrix&lt;T&gt;&amp; m1, const Matrix&lt;T&gt;&amp; m2) {<br>    if (m1.cols != m2.rows) <br>        throw std::invalid_argument(&quot;Matrix dimensions incompatible.&quot;);<br>    <br>    Matrix&lt;T&gt; result(m1.rows, m2.cols);<br>    <br>    auto l = [&amp;m1, &amp;m2, &amp;result](size_t row, size_t col) {<br>        auto res = T{};<br>    <br>        for (size_t i = 0; i &lt; m1.cols; i++)<br>            res += m1(row, i) * m2(i, col);<br>        <br>        result(row, col) = res;<br>    };<br>    <br>    std::vector&lt;std::jthread&gt; jobs;<br><br>    for (size_t r = 0; r &lt; m1.rows; r++) <br>        for (size_t c = 0; c &lt; m2.cols; c++)<br>            jobs.emplace_back(l, r, c);<br>    <br>    return result;<br>}</pre><p>This gets really stupid really fast:</p><ul><li>As I explained before, a thread/worker needs a task, and we need to define a blueprint for that task in the form of a callable. My callable is designed such that it works on a single row-column dot product on each call, as illustrated by its parameters. Therefore, according to this design, each new thread will handle a single dot product.</li><li>I then create a vector that will hold my threads. I make use of std::jthread instead of vanilla std::thread, as that allows me to not write .join()&#39;s. It automatically takes care of waiting and merging. By the way, try not to use std::thread. RAII for life!</li><li>In the loop, for each column in each row, I emplace_back() a std::jthread in which the callable, row and column are passed.</li><li>For a 3x3 times 3x3, I will have spawned 9 threads for 9 dot products. That is just a tiny bit of addition and multiplication per thread. Clearly, I wrote about this program before even understanding the cost of std::thread.</li></ul><p>See, operations like addition are executed extremely efficiently by the CPU. That is literally one of its main jobs. But the task given to the thread isn’t the entire work itself. Spawning the OST itself is also a mighty task. The request for an additional worker must be given to the OS and upon availability, an additional thread becomes ready to execute tasks within microseconds (10⁻⁶). Compare that to the <em>nano</em>seconds (10⁻⁹) it takes for the CPU to speed through sums and products. This makes std::thread a double edged sword. It can cut down work done per unit time significantly, but getting one ready in the first place is quite expensive.</p><p>In this case, this means that the CPU actually spent most of the execution time spawning and getting the threads ready, not calculating the actual dot products. Through this example, I hope you can yourself reach to the conclusion that std::thread is best used when the task significantly outweighs the spawning costs.</p><p>But wait, there is more — HTs (hardware threads, if you were skimming) are a limited resource. I’ve got an CPU with 4 p-cores (2 threads/core) and 8 e-cores (1 thread/core) on my laptop, so that is a maximum of 16 threads. Your mileage may vary. This is why the target system is also an important variable to consider before integrating multithreading into your program. Usually, the more workers you can get to complete complex calculations, the better. But the final performance will naturally vary due to the hardware constraints.</p><p>My code did not care about the number of threads available to me. I just pushed more and more threads depending on the dimensions of the matrices. For a 4x4 times 4x4, that is 16 threads, just within my personal hardware limits. But any bigger than that, and two things would drag me down — The first is the resource cost of spawning a thread (stack memory, spawn time etc.). Secondly, each HT will have to context switch between multiple OSTs in order to maintain the illusion of simultaneous execution, which introduces a lot of overhead.</p><p>At this point, before reading any further, I would like to invite you to think of ways this code could actually work and properly use the resources (threads) available.</p><p>If you thought of chunking/grouping work based on the matrix dimensions or something along those lines, you get a C++ grade!</p><p>Here is that approach:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee28dac8225f733e55f31a712ebbacbc/href">https://medium.com/media/ee28dac8225f733e55f31a712ebbacbc/href</a></iframe><p>And here is the breakdown:</p><ul><li>Firstly, in order to check the number of threads available to me, I use std::thread::hardware_concurrency(), which returns an integer amount.</li><li>I ceiling divide the number of rows in the left matrix by this thread count to get the row_thread_ratio. This ratio will determine the amount of work to be handled by each thread.</li><li>Notice that for small matrices, this ratio can be quite small. 8 threads for a 4x4 times 4x4 matrix multiplication equates to a ratio of half a row per thread. That is just stupid, because it shows that (a) we don’t need that many threads anyways and (b) processing half a row at a time is plain inefficient from the CPU’s perspective.</li><li>That is why I make use of a minimum chunk size of 4. For example, 30 rows and 8 threads mean a chunk size less than 4. Instead of having each thread handle way too small chunks, I set a minimum chunk size so that each thread can actually save on the execution time.</li><li>Again, I create an std::vector to store std::jthread&#39;s.</li><li>Then, a loop goes through the number of available threads and allocates the correctly-sized chunk of work to each thread. As you can see, this time, I have written the lambda directly inside the thread creation statement. Also notice that I haven’t passed any extra arguments inside .emplace_back() because the required values are captured by the lambda instead.</li><li>Apart from the different looping ranges, the multiplication algorithm is basically the same.</li></ul><p>I feel proud to share the performance comparison with you. Both versions were run with the highest compiler optimization settings, vectorization enabled, and my CPU (i5–12500H Laptop) on turbo -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*beuEe_2gsBkWo9bCABQibg.png" /><figcaption>cubic curve go brrrr</figcaption></figure><p>Multiplying two 1180x1180 matrices together is 8 times faster with the multi-threaded version. Again, this result is system dependent but the takeaway is clear — There is massive potential for performance improvements by implementing concurrency.</p><p>The volatility you see in the red curve by the end is due to my CPU throttling. I was pushing it to its limits, with temperatures at a consistent (and quite harmful) 93–95 degrees Celsius. But I would do it again. For science :) The alignment with the theoretical curve is still clear. It is not discernible in this graph, but before n=160, the naive approach is consistently faster, with much higher performance in multiplying smaller matrices. But now you know why that is. You do remember, right?</p><p>With this result, I was ready to upgrade my matrix multiplication function to use multithreading. But a question remained — the two matrices don’t necessarily need to be square, so what would be the threshold to cross for me to opt for the multithreaded version? At first, I thought of using 160 x 160 = 25600 as my threshold, because that would be the number of dot products (160 rows of Matrix A times 160 columns of Matrix B) that would be carried out.</p><p>But that is only part of the full picture. How many pairs would I be multiplying and adding together in that dot product? For a 160x160 matrix, that’s 160 multiply-add operations per dot product and over 4 million in total.</p><p>But in the case of 160x2 times 2x160, that is just 160 x 2 x 160 = 51200 operations! But if I had used my older threshold, multithreading would have triggered for a matrix that doesn’t need it at all, leading to poor performance. This means that using the total number of operations, rather than number of dot products, is the right way to choose between standard and multithreaded approaches.</p><p>For an <em>M</em>×<em>N</em> matrix multiplied by an <em>N</em>×<em>P</em> matrix, the total operation count is <em>M</em>×<em>N</em>×<em>P</em>. And since I know the threshold for my system was 160³ operations, that is the number I used.</p><p>For transparency, here is the script I used for benchmarking and graphing the results, in C++ and Python respectively -</p><pre>int main() {<br>	Timer t, g;<br>	for (int i = 5; i &lt; 1200; i += 25) {<br>		auto m1 = mat_random_int_range(i, i, 1, 9);<br>		auto m2 = mat_random_int_range(i, i, 1, 9);<br>		float sum_naive = 0.0f;<br>        for (int repeats = 0; repeats &lt; 10; repeats++) {<br>            t.reset();<br>            auto slow = m1 * m2;<br>            sum_naive += t.elapsed();<br>        }<br>        std::cout &lt;&lt; i &lt;&lt; &quot;, &quot; &lt;&lt; sum_naive / 10.0f &lt;&lt; std::endl;<br>    }<br>    <br>	for (int i = 5; i &lt; 1200; i += 25) {<br>		auto m1 = mat_random_int_range(i, i, 1, 9);<br>		auto m2 = mat_random_int_range(i, i, 1, 9);<br>		float sum_multi = 0.0f;<br>		for (int repeats = 0; repeats &lt; 10; repeats++) {<br>			g.reset();<br>			auto fast = m1.fast_mult(m2);<br>			sum_multi += g.elapsed();<br>		}<br>		std::cout &lt;&lt; i &lt;&lt; &quot;, &quot; &lt;&lt; sum_multi / 10.0f &lt;&lt; std::endl;<br>	}<br>}</pre><ul><li>If you are wondering why I am using two different loops that are almost doing the same thing, I wanted to separate the two modes of execution (single thread vs multithread) so that each result isn’t influenced by the other.</li><li>Also, in this benchmark, fast_mult() uses the multithreaded version and the *operator uses the standard one.</li></ul><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>plt.style.use(&#39;seaborn-v0_8-deep&#39;)<br>import pandas as pd<br><br>col_sizes = &quot;n_x&quot;<br>col_naive = &quot;time_x&quot;<br>col_multi = &quot;time_y&quot;<br>data = pd.read_csv(&quot;data.csv&quot;)<br>data.columns = data.columns.str.strip()<br>print(data.head())<br>sizes = data[col_sizes]<br>naive = data[col_naive]<br>mt = data[col_multi]<br>constant = naive.iloc[-1] / (sizes.iloc[-1] ** 3)<br>ideal_times = constant * (sizes ** 3)<br>plt.plot(sizes, ideal_times, &#39;--c&#39;, label=&#39;O(n^3) reference&#39;, linewidth=1)<br>plt.plot(sizes, naive, &#39;r&#39;, label=&#39;Naive&#39;, linewidth=2)<br>plt.plot(sizes, mt, &#39;b&#39;, label=&#39;Multi-threaded&#39;, linewidth=2)<br>plt.vlines(160, 0, 4, &#39;g&#39;, linestyles=&quot;:&quot;, label=&quot;Diverging point (n≈160)&quot;)<br>plt.xlabel(&quot;nXn Matrix Multiplication&quot;)<br>plt.ylabel(&quot;Execution Time (s)&quot;)<br>plt.legend(frameon=True, loc=&#39;upper left&#39;)<br>plt.title(&quot;Matrix Multiplication: Naive vs Multi-threaded&quot;)<br>plt.grid()<br>plt.tight_layout()<br>plt.show()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a66bc8c0cde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ concepts I learnt about and used while building a LinAlg library]]></title>
            <link>https://atharvesting.medium.com/c-concepts-i-learnt-about-and-used-while-building-a-linalg-library-db982e76cd65?source=rss-a2c7b71eea75------2</link>
            <guid isPermaLink="false">https://medium.com/p/db982e76cd65</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[stl]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Atharv Rawat]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 10:44:47 GMT</pubDate>
            <atom:updated>2026-06-05T10:44:47.495Z</atom:updated>
            <content:encoded><![CDATA[<h3>C++ concepts I learnt about and used while building a LinAlg library (Coding Notes June 5)</h3><h3>std::move in Object Instantiation</h3><p>A powerful and optimal way for instantiating an object with non-trivial data:</p><pre>Vector(std::vector&lt;T&gt;&amp;&amp; rray)<br>	: vec(std::move(rray)), ...</pre><ul><li>std::move transfers ownership of the data to the object attribute. This saves us the cost of copying the value.</li><li>Note: For this work, vectors being passed in the constructor must be temporary. <em>Rvalues</em> to be more specific. &amp;&amp; is known as the rvalue reference, as opposed to &amp; which is the more common lvalue reference. Rvalues references signal the compiler that the data is temporary, so moving its resources to a different place is alright.</li></ul><p>Here is an example:</p><pre>Vector&lt;int&gt; myVector(std::vector&lt;int&gt;{ 1,0,0 });<br>// as opposed to:<br>std::vector&lt;int&gt; v1 = {1, 0, 0};<br>Vector&lt;int&gt; myVector(v1); // THIS WILL NOT WORK!</pre><ul><li>The first line works because the data is clearly anonymous, i.e. it has no label or variable tied to it, making it an rvalue.</li><li>The reason passing an initialized vector won’t work is that move semantics work with rvalues or temporary values, not lvalues or permanent ones.</li><li>One can imagine moving v1&#39;s data to the Vector object only to mistakenly try later to access v1 when the data it is supposed to store isn&#39;t there anymore!</li></ul><h3>Null Value of a Template Datatype</h3><p>While working with templates, one will certainly come across the need to initialize data of the same type with a zero value. The thing is, this zero value differs in many datatypes. For int, it is actually just 0. But for float and double, we use 0.0f and 0.0 respectively.</p><p>In order to maintain cohesion in our code and avoid initializing a known zero value for an unknown template type, we use T{}, or whatever else one is using as the template variable name. This default-initializes the type.</p><h3>Iterators for Object</h3><p>I was working on a Vector class which used std::vector to store the actual vector (we&#39;ll call that atrribute vec) in an attribute. I found myself constantly writing Vector.vec.begin() and Vector.vec.end() in order to traverse the vector data. If operator overloading allowed random access to my std::vector inside the object, surely there must be a way to also quickly access its iterator.</p><p>The solution is not as elegant as I thought it would be, but it is thankfully very straightforward:</p><pre>using iterator = std::vector&lt;T&gt;::iterator;<br>using const_iterator = std::vector&lt;T&gt;::const_iterator;<br><br>iterator begin() { return vec.begin(); }<br>iterator end() { return vec.end(); }<br><br>const_iterator begin() const { return vec.begin(); }<br>const_iterator end() const { return vec.end(); }</pre><ul><li>Firstly, I set up type aliases for iterator (read and update) and const_iterator (read only).</li><li>Then it is as simple as defining two class methods that return the iterators of the underlying std::vector.</li><li>Note: Similar to other operator overloads, we establish two versions of the same function, one which allows us to read and update values using the iterators and the other that only allows reading.</li></ul><p>Q: How does the program choose which one to use?</p><h3>std::reduce</h3><pre>// std::reduce defined in &lt;numeric&gt;<br>static float magnitude(const std::vector&lt;T&gt;&amp; arr) {<br>    auto square_sum = std::reduce(std::execution::par_unseq,<br>	arr.begin(),<br>	arr.end(),<br>	T{ 0 },<br>	[](T total, T num) { return total + num * num; }<br>    );<br>    return static_cast&lt;float&gt;(std::sqrt(square_sum));<br>}</pre><ul><li>std::reduce is an alternative to std::accumulate for &quot;reducing&quot; the contents of a container to a single value. The key difference between is the sequence of operations. While std::accumulate guarantees left-to-right aka sequential processing, std::reduce can process elements out of order in order to take advantage of hardware optimisations like vectorization and multi-threaded parallel operations.</li><li>Naturally, the arbitrary order necessitates operations that are both associative and commutative, which in this case is addition.</li><li>std::reduce takes a parallelization policy (which basically defines the kind of parallel configuration to use) whose options are defined in &lt;execution&gt;. In this case, std::execution::par_unseq refers to the Parallel Unsequenced Policy, which is the fastest execution policy (in general).</li><li>As for the arguments, we state the execution policy, container iterators, starting value, and the operation lambda or function. This lambda function must take an accumulator and element as arguments.</li></ul><h3>std::transform</h3><p>Best way to perform element-wise operations with two containers.</p><pre>// std::function defined in &lt;functional&gt;<br>// std::tranform defined in &lt;algorithm&gt;<br><br>// This is a template class method!<br>Vector&lt;T&gt; element_wise(const Vector&amp; other, std::function&lt;T(T, T)&gt; func) const {<br> if (!dims_match(other)) <br>  throw std::invalid_argument(&quot;Vector dimensions must match.&quot;);<br> <br> Vector&lt;T&gt; result(this-&gt;dim);<br> std::transform(vec.begin(), vec.end(), <br>  other.begin(), result.begin(), <br>  func<br> );<br> return result;<br>}</pre><ul><li>std::transform takes the iterators for the first container, start iterator of the second, start of the target container, and the operation function.</li><li>Note that std::transform blindly assumes that the second container has at least as many elements as the first one. If that is not the case, it leads to undefined behaviour.</li></ul><p>Used for element-wise addition and subtraction of two vectors:</p><pre>Vector&lt;T&gt; operator+(const Vector&amp; other) const {<br>    return element_wise(other, std::plus&lt;T&gt;());<br>}<br><br>Vector&lt;T&gt; operator-(const Vector&amp; other) const {<br>    return element_wise(other, std::minus&lt;T&gt;());<br>}</pre><h3>std::inner_product for Dot Product</h3><p>Using the in-built function is best for calculating dot products:</p><pre>// std::inner_product defined in &lt;numeric&gt;<br>T operator*(const Vector&amp; other) const {<br>    if (!dims_match(other)) <br>  	throw std::invalid_argument(&quot;Vector dimensions must match.&quot;);<br>		<br>    return std::inner_product(vec.begin(), vec.end(), other.begin(), 0);<br>}</pre><ul><li>All it needs are the start and end iterators of the first container, start of the second, and the initial value.</li></ul><h3>Variadic Templates</h3><p>Writing a function that takes a variable number of arguments requires using variadic patterns. In the case where the exact datatype isn’t known in advanced, using variadic templates are the safest way, as they ensure type safety and compile-time optimisation.</p><pre>template &lt;typename... Args&gt;<br>static std::vector&lt;Vector&lt;float&gt;&gt; gram_schmidt(Args&amp;&amp;... args) <br>{<br>	std::vector&lt;Vector&lt;T&gt;&gt; input_vectors{ std::forward&lt;Args&gt;(args)... };<br>	// code...<br>}</pre><ul><li>template &lt;typename... Args&gt; declares the template parameter pack. The ellipsis notation makes Args a placeholder for a variable amount of datatypes.</li><li>Args&amp;&amp;... args declares the function parameter pack.</li><li>In this case, &amp;&amp; is not used as an rvalue reference which was discussed in a previous note. Here, they indicate a <em>universal reference</em>, which is has the <a href="https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers">type </a><a href="https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers">T&amp;&amp; for some deduced type T</a>. In other words, it is a universal reference if they is type deduction involved, like there is in our function. This makes Args a deduced template parameter.</li><li>The ... after &amp;&amp; makes args the parameter pack.</li><li>In order to unpack the parameters passed, we use std::forward in order to cast our variable inputs properly. lvalues and rvalues are significant here. If an argument passed is an rvalue, the value can just be moved to the target vector. If its an lvalue, the data will need to be copied. Consider this snippet:</li></ul><pre>auto v1 = Vector(___); <br>auto v2 = Vector(___);<br>gram_schmidt(v1, std::move(v2));</pre><ul><li>In this case, v1 is an lvalue (because it has a name) and std::move(v2) is an rvalue. std::forward automatically determines that in order to optimise the unpacking.</li><li>The ellipsis after std::forward&lt;Args&gt;(args)... instructs the compiler to repeat this casting operation for each piece of data passed in the parameter pack. This is how the pack is expanded behind the scenes using the given line:</li></ul><pre>std::vector&lt;Vector&lt;T&gt;&gt; input_vectors{  <br>    std::forward&lt;T1&gt;(v1),  <br>    std::forward&lt;T2&gt;(v2),  <br>    std::forward&lt;T3&gt;(v3) <br>};  // this is an example where 3 arguments were passed.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*343KFyZuYsYzuW5u" /><figcaption>Photo by <a href="https://unsplash.com/@jstrippa?utm_source=medium&amp;utm_medium=referral">James Harrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db982e76cd65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I built ChatGPT’s grandfather]]></title>
            <link>https://atharvesting.medium.com/i-built-chatgpts-grandfather-981e9689f38b?source=rss-a2c7b71eea75------2</link>
            <guid isPermaLink="false">https://medium.com/p/981e9689f38b</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[markov-chains]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Atharv Rawat]]></dc:creator>
            <pubDate>Sun, 31 May 2026 12:45:15 GMT</pubDate>
            <atom:updated>2026-05-31T12:45:15.652Z</atom:updated>
            <content:encoded><![CDATA[<p>I like to learn about machine and deep learning. So while conversing about LLMs with a friend of mine — who is actually quite famous and whose name rhymes with GPT — he suggested that I try to build its primitive version. A Markov Chain-based n-gram Probabilistic Text Prediction Model. I know that sounds heavy, but it’s not that deep. Trust me bro.</p><p>Take this sentence:</p><pre>How are ___?</pre><p>You probably just filled in the blank without even meaning to. What you just did is a result of thousands of hours of education and reading and exposure to the English language. What you just did is predict the next word in the sentence by considering the ones immediately before it.</p><p>That, but its digital and much dumber version, is the Markov Chain-based n-gram Probabilistic Text Prediction Model.</p><ol><li>A Markov chain is a state machine, where only the information about your current position guides what may come next.</li><li>A bigram or 2-gram model uses 1 word as context to predict the next one. The gram count <em>n</em> includes both the number of words used as context as well as the one word that is predicted. That is n-gram. In a trigram or 3-gram model, the last two words are used as context to predict the next one.</li><li>The model is probabilistic because it maps frequencies to the following words in the training phase. The more times B has succeeded A, the higher chance there is that the model will predict B after A is seen. Tying the Markov Chain into this, if the current state is A, there will be a higher chance of moving to state B as opposed to other possible states.</li><li>Finally, this model is able to predict text by using a starting word/phrase as the initial state, then predicting the next word based on patterns it “learnt” during the training phase.</li></ol><p>When I started, I decided to break down the problem and only focus on the bigram model. The sole goal was to get only that working somehow. Now, at this point, I had learnt that problem solving started with the data structure. You choose the right one, it makes your life easier. You choose wrong, you have to go to your friend for advice.</p><p>Let’s try to figure it out. Take this phrase:</p><blockquote><em>get a new friend</em></blockquote><p>Here, there are only 3 pairs that can be formed — (get, a), (a, new) and (new, friend). When the model is trained, it is supposed to read every word as a parent and the following one as its successor (<em>potential</em> successor by the way).</p><p>This means that my data structure had to store a collection of all possible parent-successor pairs for any given number of words. At this point, all the hashmap memes started to stream into my head and I decided that the map was the best way to navigate this problem :)</p><p>Note that a parent word could have many successors. “new” could be succeeded by “friend”, “playstation”, “life” etc. in a single text. Which means that our map must store not only all the parent words, but also all of the successors AND how often the successors followed the parents. Since a map only stores unique keys (which would be all of the parent words), the value part will have to store all of successors along with their respective frequencies. At this point, the hashmap memes started flooding my mind again...ok I&#39;ll stop.</p><p>The point is, the map would have to store all possible parent words as keys and then store another map as the key. The inner map will store all successors as keys and their frequencies as the values. This is what that looks like:</p><pre>map&lt; parent, map&lt;successor, frequency&gt; &gt;</pre><p>But I had to take a step back, because it still wasn’t clear how the map would be populated. How was I going to prepare the raw text data? In order to break down the problem further, I thought of stripping all the punctuation and capital letters from the text to homogenize it. Then, I could put all the words in a vector where the original order was maintained.</p><p>After that, filling up the map was extremely simple:</p><pre>map&lt;string, map&lt;string, int&gt;&gt; vector2Map(const vector&lt;string&gt;&amp; words)<br>{<br>    map&lt;string, map&lt;string, int&gt;&gt; fMap;<br>    for (size_t i = 0; i &lt; words.size() - 1; i++)<br>    {<br>        fMap[words[i]][words[i + 1]]++;<br>    }<br>    return fMap;<br>}</pre><ul><li>This snippet fMap[words[i]][words[i + 1]]++ is quite powerful and I love the C++ allows us to do this. Feel free to skip ahead if you already understand what it does.</li><li>fMap[words[i]] tries to access the string key as in words[i]. If that doesn&#39;t already exist, it creates a new key AND initializes its value with an empty map because that is already defined to be the data type for its value.</li><li>Immediately after that, it checks for the key words[i + 1] in the inner map. If that key doesn&#39;t exist, it yet again creates it AND initializes its value with 0, because the value of the inner map is defined to be an integer.</li><li>So, it accessed/created parent key, then accessed/created successor key, and finally added 1 to the inner map’s value, which automatically started at 0.</li></ul><p>After the map had been populated successfully, I was ready to use it for generating sentences. But for that, a predict() function was needed. In essence, the algorithm had to take a parent word as input and choose a successor out of all possible ones.</p><p>Since the chance of a certain successor to be chosen increased with the amount of times it actually appeared in the original text, using probability seemed obvious. So that is what I did. Literally, as easy as this:</p><pre>                 Frequency of A<br>P(word A)   =    ---------------<br>		 Total Frequency</pre><p>Firstly, I made a pass through all the frequencies in the inner map for a given parent word and added up all of them to calculate the total frequency. Then, I generated a random number <em>R</em> between 0 and 1 and made another pass, but this time, I added the probabilities for each until they added up to greater than <em>R</em>. Whichever word pushed the total over the <em>R</em>, was chosen.</p><p>At first, this approach may not seem intuitive. Don’t let the order of the word probabilities confuse you. The reason why this works is that a word with a larger frequency will naturally have a larger probability, and this larger probability will in turn have a higher chance of pushing the cumulative probability over <em>R</em>.</p><p>Here is a better way of understanding this: Imagine a line from 0 to 1 with partitions that all words create using their probabilities. These partitions have different “areas” based on their probabilities. All we are doing is generating a random number and checking in which partition it lands. Since the computer cannot do this at a glance, we use the cumulative probability to check the landing area.</p><p>Extremely helpful infographic generated by ChatGPT using the last three paragraphs as the prompt. Note that the probabilities needn’t be arranged in a sorted order:</p><p>The same logic translated to C++ code:</p><pre>void predict(string start, unsigned int word_count) override {<br>    auto&amp; fMap = model_data;  // this is our map<br>    unsigned int i = 0; string current = start;<br>		<br>    cout &lt;&lt; start &lt;&lt; &quot; &quot;;<br>		<br>    while (i &lt; word_count) {<br>			<br>        if (fMap.find(current) == fMap.end()) break;<br>            <br>            double r = randomNumGenerator();<br>            double cumulative_prob = 0.0;<br>            map&lt;string, int&gt; temp = fMap.at(current);<br>            int total = nextWordsfSum(temp);<br>            <br>            for (const auto&amp; [word, count] : temp) {<br>                cumulative_prob += (double)count / total;<br>                <br>                if (cumulative_prob &gt;= r) {<br>                    cout &lt;&lt; word &lt;&lt; &quot; &quot;;<br>                    i++;<br>                    current = word;<br>                    break;<br>                }<br>            }<br>        }<br>    cout &lt;&lt; &quot;\n\nPrediction terminated!&quot; &lt;&lt; endl;<br> }</pre><p>I had another friend of mine (this one is more privacy-focused, so no hints :) ) provide the training text. This model design worked surprisingly well. Here are some admittedly cherry-picked results:</p><blockquote><em>the school begins the teacher takes attendance and closes his school after math comes at nine</em></blockquote><blockquote><em>the playground again science notebook and a house tim mixes colors on the ball back and</em></blockquote><p>Ultimately, I was not satisfied with the output, solely because the next step towards supposedly massive improvement was right in front of me: Trigrams.</p><p>Here were some problems with my bigram code that made it quite hard to advance to trigrams:</p><ul><li>The program was hard-coded for bigrammatic predictions. Right from the very data structure used. Using std::string as the outer key meant sacrificing abstraction for arbitrary context lengths. I could only fill the map keys with single words that would help predict the next one. In all fairness, this can be solved by using std::vector as the outer key. This would have made the input scalable while keeping the inner map the same. Additionally, my initial goal was just to get bigram working, so code&#39;s limitations weren&#39;t a nasty surprise for me.</li><li>I also read into the performance implications, and it turns out that maps are incredibly inefficient for this kind of work. This is because a map is implemented as <a href="https://en.cppreference.com/cpp/container/map">a kind of binary tree</a>, whose elements are scattered across memory (heap allocation) which, for lookup, the CPU must then navigate through using pointers, leading to significant overhead and cache misses. This problem is exacerbated through the use of nested maps. Imagine navigating outer keys using pointers, then navigating inner keys using pointers, just to update the frequency count. Now imagine having to do that for thousands of words. And that is just the training phase. The same applies to the prediction phase.</li></ul><p>Clearly, my choice for the data structure was suboptimal. Reaching out to my friend became unavoidable.</p><p>More on that in the next blog. Stay tuned!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*POquLGNi62qSYMV9" /><figcaption>Photo by <a href="https://unsplash.com/@freshvanroot?utm_source=medium&amp;utm_medium=referral">Rolf van Root</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=981e9689f38b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Composition over Inheritance]]></title>
            <link>https://atharvesting.medium.com/composition-over-inheritance-f3c9f8cda067?source=rss-a2c7b71eea75------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3c9f8cda067</guid>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[strategy-pattern]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Atharv Rawat]]></dc:creator>
            <pubDate>Sat, 16 May 2026 15:17:32 GMT</pubDate>
            <atom:updated>2026-05-16T15:17:32.624Z</atom:updated>
            <content:encoded><![CDATA[<p>C++ has a lot of double-edged swords. These features abstract the process of turning the sharp edge on yourself, so that you can destroy yourself with greater efficiency.</p><p>Well, I threw away one of those swords in time, and its name was <em>Inheritance</em>. It’s a powerful tool, no doubt, but it was overkill ;) for my needs.</p><p>Inheritance showed up neatly as I was building my first proper C++ game. For now, my definition of proper is a console game with gravity, collision detection, and ASCII for those high quality textures. My game is simple — Balls fall, you catch, score up. With powerups and debuffs to spice things up.</p><p>Initially, OOP was my best friend. I effortlessly created a Fallable class that my balls and powerups would inherit. This class defined all the common properties and behaviours, like current x and y positions, collision detection logic, etc. My Ball and PowerUp classes inherited this. The reason inheritance attracted me was its intuitiveness. Examples like <em>Mammal-is-Animal</em> and <em>Dog-is-Mammal</em> sat right with me. Unfortunately, I forgot the significance of <em>Car-has-Engine</em> (hint).</p><p>Anyway, since the falling and catching logic was fairly straightforward (I owe this confidence to <a href="https://www.youtube.com/watch?v=xW8skO7MFYw&amp;t">OneLoneCoder</a>), I moved on to creating the actual powerups.</p><p>Before I proceed, it’d be best if you see some of the relevant code so that you know exactly what is going on -</p><p>The Fallable class:</p><pre>class Fallable {<br>protected:<br>    float coordX;<br>    float coordY;<br>    float speedX;<br>    int speedY;<br>    bool inScene;<br>    short skin;<br><br>public:<br>    Fallable(int x, float y, int speedY, short skin)<br>        : coordX(x), coordY(y), speedX(0), speedY(speed), inScene(true), skin(skin) {}<br>    virtual void update(float elapsedTime) = 0;<br>    virtual void draw(wchar_t* screen, int nScreenWidth) = 0;<br>    <br>    // This function triggers something on collision. Effect upon activation.<br>    virtual void on_collision(GameManager&amp; game, bool hitBar) = 0;<br><br>    bool is_collision_bar(int barX, int barLevel, int barWidth) {<br>        // crazy advanced logic here...<br><br>    bool is_in_scene() { <br>        // damn bro let him cook..<br>        // actual code: return this-&gt;inScene; (lol)<br>    }  <br> <br> virtual ~Fallable() {}<br><br>};</pre><ul><li>on_collision() is virtual here because balls and powerups do different things when they collide with something. So the children will define the actual behaviour.</li></ul><p>The PowerUp class that inherits Fallable:</p><pre>class PowerUp : public Fallable {<br>protected:<br>    int duration;<br>    double elapsedTime;<br>    bool isActive;<br><br>public:<br>    PowerUp(int speed, short skin, int duration)<br>        : Fallable(randomNumGenerator(false, 1, nScreenWidth - 2), <br>            0, speed, skin), duration(duration), isActive(false), elapsedTime(0) {<br>    }<br>    <br>    virtual void deactivate(GameManager&amp; game) = 0;<br><br>    // More methods go here...<br>};</pre><p>It looks quite rosy, right? PowerUp rightfully inherits Fallable while adding some relevant data and behaviour of its own, like duration, elapsedTime and state. Notice that PowerUp, just like Fallable is an abstract class, meaning that this blueprint cannot be applied directly, as there is data and behaviours that haven&#39;t been defined yet. PowerUp does nothing about Fallable&#39;s on_collision() virtual function because naturally, the effect-upon-collision is totally dependent on the kind of powerup.</p><p>It goes without saying, but I want you to understand that this design set up the need for another layer of inheritance. Since each powerup has different behaviours upon activation, I had to write another set of actual powerup classes that inherited PowerUp.</p><p>That is what I did here:</p><pre>class PUdoubleBar : public PowerUp {<br>public:<br>    PUdoubleBar() : PowerUp(13, 0x002B, 7) {}<br><br>    void on_collision(GameManager&amp; game, bool hitBar) {<br>        if (hitBar &amp;&amp; game.bar.nWidth &lt;= 20) {<br>            isActive = true; inScene = false; elapsedTime = 0;<br>            game.bar.transform(2);<br>        }<br>    }<br>    <br>    void deactivate(GameManager&amp; game) {<br>        if (game.bar.nWidth &gt; 10) game.bar.transform(0.5);<br>    }<br><br>    ~PUdoubleBar() {}<br>};<br><br>// and again<br>class PUdoublePoints : public PowerUp {<br>public:<br>    PUdoublePoints() : PowerUp(13, 0x0058, 10) {}<br>    <br>    void on_collision(GameManager&amp; game, bool hitBar) {<br>        if (hitBar) {<br>            isActive = true; inScene = false; elapsedTime = 0;<br>             game.nScoreMultiplier = 2;<br>        }<br>    }<br> <br>    void deactivate(GameManager&amp; game) {<br>        if (game.nScoreMultiplier &gt;= 2) game.nScoreMultiplier /= 2;<br>    }<br>    <br>    ~PUdoublePoints() {}<br>};<br><br>// aaaand againnn :(<br>class PUenhancedSpeed : public PowerUp {<br>public:<br>    PUenhancedSpeed() : PowerUp(13, 0x2192, 7) {}<br>    <br>    void on_collision(GameManager&amp; game, bool hitBar) {<br>        if (hitBar) {<br>            isActive = true; inScene = false; elapsedTime = 0;<br>            game.bar.nSpeed *= 1.25;<br>        }<br>    }<br>    <br>    void deactivate(GameManager&amp; game) {<br>        game.bar.nSpeed /= 1.25;<br>    }<br><br>    ~PUenhancedSpeed() {}<br>};</pre><p>I can guarantee that you had one of these three reactions just now:</p><ul><li>You either did not see anything wrong with this.</li><li>Or, you sensed something was wrong. There seems to be a bunch of repetition.</li><li>Orrrr, you just took your head in your hands and shed a tear or two.</li></ul><p>Whatever reaction you just had, you are right. Think about which problems or better, which <em>patterns</em> you can spot here before proceeding.</p><p>Firstly, the constructors used in the final powerups add nothing to their data or functionality. I am just calling PowerUp&#39;s constructor. In fact, I am initializing different values for speed, skin and duration within the new classes. That&#39;s pretty bad, because that is exactly what the PowerUp constructor is meant to do.</p><p>Secondly, each powerup has exactly two methods that define custom behaviour — on_collision() (effect upon activation. I know the name sucks), and deactivate().</p><p>Finally, and perhaps most importantly, all of them change something within the GameManager class upon activation. And for our purpose, this detail is crucial: that is all they do.</p><p>All of these problem patterns point (a lil’ alliteration) to the same solution. Let’s see how they help us figure it out.</p><p>(1) The use of the exact same constructors is the first hint of redundancy. This already tells us that inheritance is not providing us with additional value. Maybe there is a way to use PowerUp directly?</p><p>(2) Each powerup having only two functions that define custom behaviour. If only there were a way to use the same class and yet have different behaviour? Wait, isn’t that the point of using classes after all? Turns out, I took my PowerUp class for granted in order to apply a shiny concept and be able to claim that I wrote some complicated code.</p><p>So let’s go back to what the basics taught us: If I create a triangle class, I should be able to create objects with different side dimensions. How will I achieve that? By taking the dimension data as arguments in the constructor.</p><p>Now, if I create a PowerUp class, I should be able to create objects with different behaviours. How will I achieve <em>that</em>? By passing behaviour data as arguments in the constructor!</p><p>I guess it helps to know (and it is probably time for me to remind you) that functions can also take other functions as arguments. Since we have only two functions (on_collision() and deactivate()) that need to be custom, we only need to pass those in the PowerUp constructor. This is an example of <em>Composition over Inheritance</em> - specifically, the Strategy Pattern, where behaviours are injected as callables instead of being defined in subclasses.</p><p>Composition over Inheritance is a software design principle which formally states that complex behaviours should be implemented by combining components rather than inheriting behaviour from the parent class. Informally, it is defined (by me) as <em>Why have children when you can do the crying yourself?</em></p><p>Here is what I am doing in my new PowerUp class:</p><pre>// #include &lt;functional&gt; is mandatory on top.<br><br>class PowerUp : public Fallable {<br>protected:<br>    int duration;<br>    double elapsedTime;<br>    bool isActive;<br>    std::function&lt;void(GameManager&amp;)&gt; activateCallback;<br>    std::function&lt;void(GameManager&amp;)&gt; deactivateCallback;<br><br>public:<br>    PowerUp(int speed, short skin, int duration,<br>        std::function&lt;void(GameManager&amp;)&gt; onActivate,<br>        std::function&lt;void(GameManager&amp;)&gt; onDeactivate)<br>        : Fallable(randomNumGenerator(false, 1, nScreenWidth - 2), 0, speed, skin), <br>            duration(duration), isActive(false), elapsedTime(0),<br>            activateCallback(onActivate), deactivateCallback(onDeactivate) {}<br><br>    void on_collision(GameManager&amp; game, bool hitBar) {<br>        if (hitBar) {<br>            isActive = true; elapsedTime = 0; inScene = false;<br>            if (activateCallback) activateCallback(game);<br>        }<br>    }<br>    <br>    void deactivate(GameManager&amp; game) {<br>        if (deactivateCallback) deactivateCallback(game);<br>    }<br>    <br> // unimportant methods...<br><br>};</pre><p>Quick overview of what matters in this new class:</p><ul><li>In order to be able to pass functions as arguments, we need the &lt;functional&gt; header which defines std::function.</li><li>Through the parameter std::function&lt;void(GameManager&amp;)&gt; onActivate, I am telling the compiler to expect a <em>callable</em> (function, function pointer, or lambda) that takes a GameManager object as reference and returns nothing.</li><li>Since it is possible that a non-existent function is passed, we will first check if a proper function actually exists before running it. As evident in the lines if (activateCallback) activateCallback(game); and if (deactivateCallback) deactivateCallback(game);.</li><li>Finally, we can address point (3), which was that each powerup was only changing something within the GameManager class. While this can be attributed to good design, it also means that we are able to define our parameter for onActivate and onDeactivate to just be GameManager&amp;. If a powerup needed access to something more than that, then the design wouldn&#39;t have worked without non-trivial refactoring.</li></ul><p>That is it. This is what makes our PowerUp class customizable. Instead of having a child class which contains these key behaviours, we directly told the PowerUp class how to behave by handing the behaviour to it outright. It is still important to mention that using std::function is not the perfect solution as it brings its own overhead. But for the purpose of readability and maintainability, this works really well.</p><p>There are two common ways to pass the functions. We can either write a normal function like we did in the inheritance code. Or we can make use of lambdas. The approach depends on the rest of your code architecture. Since I used the <a href="https://en.wikipedia.org/wiki/Factory_method_pattern">factory pattern</a> to create objects, it made sense to use lambdas instead (see <a href="https://github.com/atharvesting/mini-projects/blob/main/Pong_Game/Pong_Game.cpp">full game code</a> for a better idea if you’re curious). (As I was writing this, I found out that plain function pointers would have been more performant here. Since my lambdas <a href="https://www.geeksforgeeks.org/cpp/lambda-capture-clause-in-cpp/">capture nothing</a>, they implicitly convert to function pointers anyways. But I had to spiritually move on from the game.)</p><p>This leads to unbelievably succinct code when creating actual powerups:</p><pre>// NOTE: this is an illustrative example and not exactly how I created objects in my game.<br><br>auto doubleBar = PowerUp(12, 0x002B, 7,<br>                [](GameManager&amp; game) { if (game.bar.nWidth &lt;= 20) game.bar.transform(2); },<br>                [](GameManager&amp; game) { if (game.bar.nWidth &gt; 10) game.bar.transform(0.5); }<br>             );<br>auto doublePoints = PowerUp(10, 0x0058, 10,<br>                [](GameManager&amp; game) { game.nScoreMultiplier *= 2; },<br>                [](GameManager&amp; game) { game.nScoreMultiplier /= 2; }<br>             );<br>auto enhancedSpeed = PowerUp(12, 0x2192, 7,<br>                [](GameManager&amp; game) { game.bar.nSpeed *= 1.25; },<br>                [](GameManager&amp; game) { game.bar.nSpeed /= 1.25; }<br>       );</pre><p>Now, some readers may rightfully point to a little hypocrisy involved in the explanations: I claim that composition is better than inheritance, and it is being used anyways (PowerUp inherits Fallable). The point of this blog isn&#39;t to &quot;never use inheritance&quot;, but to understand when it isn&#39;t the best option, and it often isn&#39;t. Using composition, I managed to remove an entire layer of inheritance. I gave it the necessary birth control before it spawned tens of powerups/debuffs (depending on the scale of the game), all for me to take care of. In case you didn&#39;t notice, each inherited powerup took about 20 lines of code. That is over 200 lines of redundancy and a maintainability nightmare.</p><p>And that is how I survived decapitation at the hands of Inheritance. Like always, I hope that you were able to inherit some new skills and ideas from this post. But then again, be careful of what you inherit :)</p><p><a href="https://github.com/atharvesting/mini-projects/commit/88f172b8106ad5bd83055f7f578f1f07e40c4653?diff=split">Here</a> is the commit with the old approach if you are interested. And this is the <a href="https://github.com/atharvesting/mini-projects/blob/main/Pong_Game/Pong_Game.cpp">link</a> to the latest game code. I plan to write about this game as a whole soon, so keep your eyes peeled for that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rKGzdjEz6x8oECgl" /><figcaption>Photo by <a href="https://unsplash.com/@carlgonz?utm_source=medium&amp;utm_medium=referral">Carlos Gonzalez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3c9f8cda067" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Introduction to C++ Templates]]></title>
            <link>https://atharvesting.medium.com/my-introduction-to-c-templates-0dfabc262721?source=rss-a2c7b71eea75------2</link>
            <guid isPermaLink="false">https://medium.com/p/0dfabc262721</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <dc:creator><![CDATA[Atharv Rawat]]></dc:creator>
            <pubDate>Mon, 11 May 2026 09:02:08 GMT</pubDate>
            <atom:updated>2026-05-11T09:04:58.577Z</atom:updated>
            <content:encoded><![CDATA[<h3>My Introduction To C++ Templates</h3><p>A few days ago, on an impulse, I asked Gemini to provide me with a snippet of the source code underlying the std::cout function (which I now know is not a function at all). The implicit goal was to get a feel of the low-leveledness involved in writing foundation tools in C++. The explicit goal was procrastination :) Anyways, I got nothing out of the answer, which was fine with me. I did stumble across the notorious template as being one of the core concepts used.</p><p>Ever since I started learning C++, templates have been present in the back of my mind as the end game of proficiency in the language (not true of course). I remember seeing templates being used in random code I encountered and being intimidated by the capital T. Now I know that this fear was sustained entirely by ignorance, like most things in life.</p><p>This time, I decided to understand how it actually worked. What the need was. And it turned out to be so damn simple that I had to smile in shame when I realized. Templates are nothing but a tool to create functions and classes where you don’t know what kind of specific data you are going to work with. Or you do know, but there are too many and you need to work with them all the same way.</p><p>The popular way to put it is that classes are to objects what templates are to classes. In other words, templates are blueprints for creating classes. More accurately, they can be used to create blueprints for functions too (as will be shown later), but we can base our understanding starting from this thought.</p><p>Let’s consider the following helper function I wrote for testing an LC solution (№21):</p><pre>struct ListNodeInt {<br>	int val;<br>	ListNodeInt* next;<br>	ListNodeInt(int val) : val(val), next(nullptr) {}<br>};<br><br>ListNodeInt* vector_to_LL(std::vector&lt;int&gt;&amp; nums) {<br>    if (nums.empty()) return nullptr;<br><br>    ListNodeInt* START = nullptr, *q = nullptr;<br>    START = new ListNodeInt(nums[0]);<br>    q = START;<br><br>    for (int i = 1; i &lt; nums.size(); i++) {<br>        q-&gt;next = new ListNodeInt(nums[i]);<br>        q = q-&gt;next;<br>    }<br><br>    return START;<br>}</pre><p>If you are familiar with linked lists, this should feel like a walk in the park. I take a vector of integers, construct a singly non-circular linked list out of it, and return the head.</p><p>Now, a true programmer is probably already familiar with the DRY principle. So, I am not going to repeat what it means :) The problem with the given function is that it is hardcoded to work only with vectors containing integer values, as indicated by the single phrase std::vector&lt;int&gt;&amp; nums. Naturally, this would mean that the compiler would throw a type mismatch error if I try to pass a vector of characters in this function. Not only that, but the ListNode definition itself strictly holds integer values in val.</p><p>Does this mean that I will have to write an entirely new function that specially accepts character vectors? While this approach is viable and even conceptualized as “function overloading”, it is not scalable and affects code readability. Of course, because DRY, I don’t want to copy paste 5 versions of the same function so that every supported data type is covered.</p><p>I mean, look at this piece of crap:</p><pre>ListNodeInt* vector_to_LL(std::vector&lt;int&gt;&amp; nums) {<br>    // 10 lines of code...<br>}<br><br>ListNodeFloat* vector_to_LL(std::vector&lt;float&gt;&amp; nums) {<br>     // 10 lines of code...<br>}<br><br>ListNodeChar* vector_to_LL(std::vector&lt;char&gt;&amp; chars) {<br>    // 10 lines of code...<br>}<br><br>ListNodeDouble* vector_to_LL(std::vector&lt;double&gt;&amp; nums) {<br>    // 10 lines of code...<br>}</pre><p>That is about 40 lines of code just because a single word is different in each function.</p><p>Well no shit, templates are the answer. They allow you to write a single function that works for any data type. Let’s have a look:</p><p>Firstly, our new ListNode structure definition:</p><pre>template &lt;typename T&gt;<br>struct ListNode {<br>    T val;<br>    ListNode* next;<br>    ListNode(T val) : val(val), next(nullptr) {}<br>};</pre><p>Here, template &lt;typename T&gt; is the line that declares that the following class/function is a template, which means there are data type(s) within that are not known yet. Capital T is just the naming convention for that unknown datatype. You are telling the compiler that you are going to refer to this unknown datatype as T. In other words, this line tells that the following function is a template that wants to adapt to the datatype T. If you knew that the function was definitely supposed to accept some kind of container of values like vectors, lists, sets, etc., then it would be a better to use collection as placeholder instead of T (more on that later).</p><p>After that, it is just like how you normally define structs. All you do is that you use T wherever you don&#39;t know the datatype. In this case, val could hold an integer, a float, a character or anything else, but I don&#39;t know that for now, so I will just use the placeholder T. Nothing else unusual here.</p><p>Structs are just classes with public access members, so that is how we can write adaptive classes in C++ using templates. Note that such classes are actually called class templates, since they are only blueprints, remember?</p><p>Moving on to our function:</p><pre>template &lt;typename T&gt;<br>auto vector_to_LL(vector&lt;T&gt;&amp; collection) {<br>	<br>    if (collection.empty()) return (ListNode&lt;T&gt;*)nullptr;<br><br>    ListNode&lt;T&gt;* head = new ListNode&lt;T&gt;(collection[0]);<br>    ListNode&lt;T&gt;* current = head;<br><br>    for (int i = 1; i &lt; collection.size(); i++) {<br>        current-&gt;next = new ListNode&lt;T&gt;(collection[i]);<br>        current = current-&gt;next;<br>    }<br>    return head;<br>}</pre><p>Let’s go through this a line at a time to bring it home.</p><p>Firstly, this is an example of a function template, and just like with the structure, we start with template &lt;typename T&gt; to indicate that the following function will adapt to the unknown datatype T. Then, we use T in the parameter like so - vector&lt;T&gt;&amp; collection, indicating that we know a vector must be passed, but the datatype is unknown.</p><p>In the line ListNode&lt;T&gt;* head = new ListNode&lt;T&gt;(collection[0]); notice that we are clearly using the constructor defined in the structure definition. Wherever we would normally use a specific datatype like int, float or double, we use T instead.</p><p>If you look at this new function from a broader perspective, you may notice another problem. I hinted at it a couple hundred words ago: We managed to make the function adapt to the kind of data that the vectors store, but this function only works for vectors. What about any other container that is part of the standard library? Arrays? Lists? Deques?</p><p>A vector is technically also a datatype, so templates can definitely be applied to generalize this function further.</p><p>This is how it can be done:</p><pre>// The ListNode structure remains the same as the last version<br><br>template &lt;typename Container&gt;<br>auto container_to_LL(Container&amp; collection) {<br><br>    using DataType = typename Container::value_type;<br>    if (collection.empty()) return (ListNode&lt;DataType&gt;*)nullptr;<br><br>    auto it = collection.begin();<br>    ListNode&lt;DataType&gt;* head = new ListNode&lt;DataType&gt;(*it);<br>    ListNode&lt;DataType&gt;* current = head;<br><br>    for (++it; it != collection.end(); it++) {<br>        current-&gt;next = new ListNode&lt;DataType&gt;(*it);<br>        current = current-&gt;next;<br>    }<br>    return head;<br>}</pre><p>Here, there are only three major changes that you need to pay attention to:</p><ol><li>template &lt;typename Container&gt;</li></ol><ul><li>When we are trying to adapt a function to an unknown container, the template declaration should indicate that. Which is why we use Container as opposed to T, which is normally used for primitive data types. Note that this is just a naming convention used for code readability. The name we use has no effect on execution.</li></ul><p>2. using DataType = typename Container::value_type;</p><ul><li>Using (ha!) this line, we determine which type of data the container stores.</li><li>The using keyword is just a way for setting an alternative name for a datatype (just like typedef if you are familiar), which becomes necessary here because we don&#39;t know the specific datatype. We still need a way to reference it.</li><li>typename serves different purpose here compared to how it&#39;s used in the template declaration. First, let&#39;s show some empathy to the compiler. Not only will it have to deal with an unknown container, but it also doesn&#39;t know which datatype is stored within! That is a lot of ambiguity which we must help clear. If we had just used using DataType = Container::value_type; (notice that typename is missing), the compiler would have interpreted Container::value_type as a value, when it is actually a type! Thus, using typename is necessary to assure the compiler that Container::value_type returns a type.</li><li>Now, since the container is definitely a class object in C++, it stores attributes about itself, like the type of data it holds. That is what we access using the phrase Container::value_type.</li><li>To summarize, we want to use the name DataType (or any other name of your choice, even our beloved T) to reference the type of data stored <em>inside</em> the container.</li></ul><p>3. Iteration</p><ul><li>Finally, notice the way the container is traversed. We don’t use the index-based approach being used to specifically target vectors. This is because containers like list don&#39;t support index-based traversal. This means that we must use an approach that works for every container, so that our generalized function actually works generally.</li><li>For this, we use iterators .begin() and .end(). These iterators are built into each sequence-based STL container, which allows us to traverse them all using a single approach.</li><li>The premise is simple, container.begin() always points to the first element of the container. Notice the word &#39;points&#39;. This iterator returns a pointer that must be dereferenced to access the actual value, as illustrated in the line new ListNode&lt;DataType&gt;(*it). We call the structure constructor by naturally passing the dereferenced pointer as the value.</li><li>Similarly, container.end() points to the one <em>past</em> the last element of the container, which is why we loop while the current iterator is <em>not</em> equal to it.</li></ul><p>Hopefully, this blog just handed you the blueprint to writing more readable and frankly, impressive-looking C++ code. Templates have truly changed the way I approach writing OOP code in C++.</p><p>In order to practice what I had learnt, I wrote some more generalized helper functions using templates. Here they are. Feel free to look through them.</p><pre>// Traverse any container. <br>template &lt;typename Container&gt;<br>void traverse_container(Container&amp; collection) {<br><br>    using DataType = typename Container::value_type;<br>	<br>    if (collection.empty()) return;<br><br>    for (auto it = collection.begin(); it != collection.end(); it++) {<br>      std::cout &lt;&lt; *it &lt;&lt; &quot; &quot;;<br>    }<br><br>    std::cout &lt;&lt; std::endl;<br>}</pre><ul><li>Try to see why this wouldn’t work if the data stored inside the container is a structure or a class object.</li><li>Notice how damn <em>general</em> this function is. Any sequential STL container holding any primitive datatype can be passed.</li><li>We are using the exact principles discussed in the previous function. Only instead of building a linked list, we are doing something even simpler: sequential traversal.</li></ul><pre>// Traverse a linked list with any data type stored inside nodes. <br>template &lt;typename T&gt;<br>void traverse_LL(ListNode&lt;T&gt;* head) {<br>	ListNode&lt;T&gt;* current = head;<br>	<br>	while (current != nullptr) {<br>		std::cout &lt;&lt; current-&gt;val &lt;&lt; &quot; &quot;;<br>		current = current-&gt;next;<br>	}<br>	<br>	std::cout &lt;&lt; std::endl;<br>}</pre><ul><li>Nothing special here as well. The only thing we are adapting to is the datatype stored inside each ListNode.</li></ul><pre>// Delete the linked list and freeing memory<br>template &lt;typename T&gt;<br>void delete_LL(ListNode&lt;T&gt;*&amp; START) {<br><br>    if (START == nullptr) return;<br><br>    while (START != nullptr) {<br>        ListNode&lt;T&gt;* q = START;<br>        START = START-&gt;next;<br>        delete q;<br>    }<br>}</pre><ul><li>Again, we are doing nothing unusual here. It looks just like a normal LL deletion function except for big T.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0dfabc262721" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>