C++ Templates and Standard Template Library (STL): A Complete Beginner-Friendly Tutorial

C++ Templates and Standard Template Library (STL): A Complete Beginner-Friendly Tutorial

1. Introduction – Why Templates?

Imagine running a grocery shop. You use different delivery boxes for apples, oranges, and eggs. But using a separate box for every item leads to complexity. Instead, one general-purpose box that can deliver any item is more efficient.

Templates in C++ serve the same purpose: they allow you to write a single piece of code that works for multiple data types, instead of writing separate versions for int, double, string, and so on.

Templates enable generic programming — the compiler generates functions or classes for different data types automatically, so you write the logic once and reuse it everywhere.

2. What Are Templates?

A template is a generic blueprint that allows functions or classes to operate with different data types without rewriting the same code.

Think of T as a placeholder. When you call the function or create an object, the compiler replaces T with the actual type you use (int, double, string, etc.).

Syntax:

template <typename T>   // T is now a placeholder for any type

You can also write template <class T> — both typename and class mean the same thing here.

3. Function Templates

Function templates let you avoid writing the same function multiple times for different data types.

Problem (Traditional Approach): You need separate functions for each type:

int maxInt(int a, int b)       { return (a > b) ? a : b; }
double maxDouble(double a, double b) { return (a > b) ? a : b; }

The logic is identical — only the types differ. This is repetitive and hard to maintain.

Solution (Function Template): Write it once with a placeholder type T:

template <typename T>
T myMax(T a, T b) {
    return (a > b) ? a : b;
}

Now myMax(3, 7) works for int, myMax(2.5, 3.1) works for double, and so on. The compiler automatically creates the right version based on the types you pass.

Complete Example – add() Function Template:

#include <iostream>
using namespace std;

template <typename T>
T add(T a, T b) {
    return a + b;
}

int main() {
    cout << add(3, 4) << endl;              // Output: 7 (int + int)
    cout << add(2.5, 3.1) << endl;          // Output: 5.6 (double + double)
    cout << add<string>("Hello ", "World") << endl;  // Output: Hello World
}

Key points:

  • When both arguments are the same type, the compiler deduces T automatically.
  • For string, we write add<string>(...) to explicitly tell the compiler what T is, because string literals are const char* by default, not string.

4. Class Templates (Single Type)

Class templates generalize classes so they can store or operate on values of any type.

Problem (Without Templates): You write a separate class for each type:

class IntBox   { int value;   };
class FloatBox { float value; };

Solution (Class Template): One class handles all types:

template <typename T>
class Box {
private:
    T item;
public:
    void set(T value) { item = value; }
    T get() const     { return item; }
};

Usage:

Box<int> b1;
b1.set(100);
cout << b1.get() << endl;   // Output: 100

Box<string> b2;
b2.set("Apples");
cout << b2.get() << endl;   // Output: Apples

Complete Example – Single-Type Calculator:

Here both num1 and num2 must be the same type:

#include <iostream>
using namespace std;

template <class T>
class Calculator {
private:
    T num1, num2;
public:
    Calculator(T a, T b) : num1(a), num2(b) {}
    T add()      { return num1 + num2; }
    T subtract() { return num1 - num2; }
};

int main() {
    Calculator<int> obj1(10, 5);
    cout << obj1.add() << endl;       // Output: 15
    cout << obj1.subtract() << endl;  // Output: 5

    Calculator<double> obj2(10.5, 2.2);
    cout << obj2.add() << endl;       // Output: 12.7
    cout << obj2.subtract() << endl;  // Output: 8.3
}

Limitation: With Calculator<int>, if you pass 10.5 as an argument, the decimal part is silently truncated to 10. You cannot mix int and double in one object. The next section solves this.

5. Multi-Type Class Templates

Sometimes you need a class where the two parameters can be different types — for example, adding an int and a double. C++ lets you use more than one type parameter.

Syntax:

template <class T1, class T2>

Now T1 and T2 are independent placeholders. Each can be a different type.

Complete Example – Multi-Type Calculator:

#include <iostream>
using namespace std;

template <class T1, class T2>
class Calculator {
private:
    T1 num1;
    T2 num2;
public:
    Calculator(T1 a, T2 b) : num1(a), num2(b) {}

    auto add()      { return num1 + num2; }   // C++14: return type deduced
    auto subtract() { return num1 - num2; }
};

int main() {
    Calculator<int, int>       obj1(10, 5);
    Calculator<double, double> obj2(10.5, 2.2);
    Calculator<int, double>    obj3(10, 2.5);   // mixed types!

    cout << obj1.add() << endl;       // Output: 15    (int)
    cout << obj2.add() << endl;       // Output: 12.7  (double)
    cout << obj3.add() << endl;       // Output: 12.5  (double — int promoted)
    cout << obj3.subtract() << endl;  // Output: 7.5
}

How it works:

  • Calculator<int, int> — both parameters are int, so add() returns int.
  • Calculator<double, double> — both are double, so add() returns double.
  • Calculator<int, double> — mixed types. When C++ adds an int and a double, it automatically promotes the int to double, so the result is double.
  • The auto return type (C++14 feature) lets the compiler figure out the correct return type automatically.

6. Why Templates Matter

  • Reusable code: Write once, use for any type — no copy-pasting functions or classes for every data type.
  • Type safety: The compiler checks types at compile time, catching errors early.
  • Performance: The compiler generates optimized, type-specific code for each type used — no runtime overhead.
  • Foundation of STL: The entire Standard Template Library (covered next) is built using templates.

7. Introduction to STL (Standard Template Library)

In real-world applications, programmers constantly need data structures like lists, maps, stacks, and sorting algorithms. Writing these from scratch every time is time-consuming and error-prone. The STL provides these tools in a reusable and optimized form.

Definition:

STL (Standard Template Library) is a collection of template-based data structures, algorithms, and iterators that allow efficient storage, processing, and traversal of data in C++.

Three major components of STL:

  1. Containers — store collections of data: vector<T>, list<T>, stack<T>, queue<T>, map<K,V>
  2. Algorithms — operate on containers (search, sort, count): sort(), find(), count()
  3. Iterators — generic pointers that traverse containers: begin(), end()

8. STL Containers – Examples

Example 1: vector<int>

A vector is a dynamic array that grows automatically as you add elements.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> numbers;
    numbers.push_back(10);
    numbers.push_back(20);
    numbers.push_back(30);

    for (int x : numbers)
        cout << x << " ";    // Output: 10 20 30
}

Example 2: pair<T1, T2>

A pair holds exactly two values, possibly of different types. It is useful for storing related data together (like a name and age).

#include <iostream>
#include <utility>
using namespace std;

int main() {
    pair<string, int> student;
    student.first = "Ali";
    student.second = 22;

    cout << student.first << " is "
         << student.second << " years old.";
    // Output: Ali is 22 years old.
}
  • Access the first value with .first and the second with .second.
  • pair is defined in the <utility> header.

9. STL Algorithms – sort() Example

STL algorithms work on containers through iterators. The most commonly used algorithm is sort().

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> data = {4, 1, 9, 2};
    sort(data.begin(), data.end());   // sorts in ascending order

    for (int x : data)
        cout << x << " ";    // Output: 1 2 4 9
}
  • data.begin() returns an iterator to the first element.
  • data.end() returns an iterator past the last element.
  • sort() arranges elements in ascending order by default.
  • To sort in descending order, use: sort(data.begin(), data.end(), greater<int>());

10. Practice Questions

  1. Write a function template minValue(T a, T b) that returns the smaller of two values. Test it with int, double, and char.
  2. Create a class template Storage<T> with a private array of size 5, a set(int index, T value) method, and a get(int index) method. Test it with int and string.
  3. Create a vector<string>, add five city names, and print them using a range-based for loop.
  4. Sort a vector<double> containing {3.5, 1.2, 4.8, 2.1} and print the sorted result.
  5. Create a multi-type Calculator<int, double> and test add() and subtract() with mixed types.

9 thoughts on “C++ Templates and Standard Template Library (STL): A Complete Beginner-Friendly Tutorial”

  1. Nudee sceen from prettty babyHeeel sex srocking videoPorrn hhub shawna leneeHoow tto gett my
    breast bigher without surgeryExhibitionisem hentaiThee pleasure palace tawmpa flTeeen ykung booy ude ppic
    freeLingerie man preferTubee member ssex picsPornstar monica
    mayhemTranny seex club tampaFree college thumbsDadd annd dqughter xxxx moviesAsperges aand frequncy oof pornography addictionBlachk cocdk fucks asianFemdom bsdm
    vidsFreee mae porn streaming moviesRenmee
    olstead in bikiniTeeen choise awarrs 2010Mayy groows upp arult
    sexLedbian suirt orgy sluut loadNudee nickelodeeon girlsFrran dreescher
    nakerd picsWholke nnew york strikp recipeFreee porfn no signupp orr chargeTiit
    cuum tubeguideMature housewie annd younng boyFreee xxxx for mexicanSexxy asin oof novca scotiaEllen nordegrn nakedPornsttar photoesBeads
    uup heer assWoork myy cockFree porn pcts oof x girlfriendsLessbian spanksCoules
    havig ssex i imagesIn jjob modeliing nashville teenClothed cmshot compliationSexul additionRedtuube girl suhks pixza boys cockBreast cancer june 7Rennt a
    hospital grade breqst pumpAlbaa jessic sexyUnwillinmg girrl ssex picturesMr.
    Hands – fuckingAnswer hatassment issie sexualMoost impresszive cumshotsAnimadcos
    dibjos grati pornOrlaando bloom naked on beachHoww tto talk heer int anawl sexFrree femdom video painFirt cum
    compilationFruijt enzyme facial maskModeels n celebs nudeDumbb sex videoVifgin radio christtian ox27connellHott nuxe cheerleader picsSexx sxenes nude celebritiesConvertablle hopler bottoom grain trailorsBalks deerp matureAmasteur camm
    ckuple universityNuude prtegnant women titsCruel painbful angry abusive ssex vvids
    https://ficktube.cc/thema-judy Oppen shaged pussiesLadyboys masturbating cumVintae lingerje adsMasery bys hones for teenDisne krduger nud sceneGirlss fuckiung inn the
    ofrice photosThumnb securityAmature dunk ssex videosJaclyn nakedPorbography revenueInterrzcial cucoold
    humiliation storiesHand joob ccum sho vidsChanging rom fhck videoHistory off aapple bokttom jeansManhattan puebla stripWebcam
    pajty porrn pocs freeMedidith viefa nakedGrls vzcumm pussyHoow tto gget
    horry pornSnookii naked frfee picturesIn libray
    sexSpringfield 9mm with thbumb safetyAdult conten monitoring softwareBookwoorm asianAduylt
    free nline read storyManddingo fuckss black girlsHollooween pussyRertube amatewur
    stripCo2 inflation fetishFace skap hardcore slutloadHipster
    teenCourtney frisl bkini maximGiirl onn girrl spankFreee gheto tern porn clipsWomen bteast photoHuuge gayy cock photops picsLesbians succking monster
    titsMature girl pictureMasturbation scene in movieBustfy escort service orane countyPenis ttoo deep

  2. Woww hat wwas unusual. I juhst wrote aan vwry lobg commment but after I clixked sibmit myy cmment didn’t
    appear. Grrrr… well I’m not wrditing alll thhat over
    again. Regardless, juist wanted tto sayy excellent
    blog! xnxx

Leave a Reply

Your email address will not be published. Required fields are marked *