{"id":17825,"date":"2025-04-02T09:00:00","date_gmt":"2025-04-02T04:00:00","guid":{"rendered":"https:\/\/afzalbadshah.com\/?p=17825"},"modified":"2025-04-02T09:00:00","modified_gmt":"2025-04-02T04:00:00","slug":"c-templates-and-standard-template-library-stl-a-complete-beginner-friendly-tutorial","status":"publish","type":"post","link":"https:\/\/afzalbadshah.com\/index.php\/2025\/04\/02\/c-templates-and-standard-template-library-stl-a-complete-beginner-friendly-tutorial\/","title":{"rendered":"C++ Templates and Standard Template Library (STL): A Complete Beginner-Friendly Tutorial"},"content":{"rendered":"\n<p>Imagine running a grocery shop. You use different delivery boxes for apples, oranges, and eggs etc. 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 writing a single piece of code that works for multiple data types.<\/p>\n\n\n\n<p>Templates enable generic programming, letting the compiler generate functions or classes for different data types automatically.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What Are Templates?<\/h2>\n\n\n\n<p>Template help you write code that can automatically adjust to different data types, making your programs cleaner, shorter, and more efficient.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>A template in C++ is a generic blueprint that allows functions or classes\nto operate with different data types without rewriting the same code.\n<\/code><\/pre>\n\n\n\n<p>In code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>template &lt;typename T&gt;\n<\/code><\/pre>\n\n\n\n<p>This introduces <code>T<\/code> as a placeholder type.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Function Templates<\/h2>\n\n\n\n<p>Function templates help avoid writing the same function multiple times for different data types.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example (Traditional Approach):<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>int maxInt(int a, int b);\ndouble maxDouble(double a, double b);\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Function Template:<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>template &lt;typename T&gt;\nT myMax(T a, T b) {\n    return (a &gt; b) ? a : b;\n}\n<\/code><\/pre>\n\n\n\n<p>The compiler automatically creates versions of this function based on the types used.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Complete Example:<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\ntemplate &lt;typename T&gt;\nT add(T a, T b) {\n    return a + b;\n}\n\nint main() {\n    cout &lt;&lt; add(3, 4) &lt;&lt; endl;\n    cout &lt;&lt; add(2.5, 3.1) &lt;&lt; endl;\n    cout &lt;&lt; add&lt;string&gt;(\"Hello \", \"World\") &lt;&lt; endl;\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Class Templates<\/h2>\n\n\n\n<p>Class templates generalize classes to store or operate on values of any type.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example Without Templates (Repetitive):<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class IntBox { int value; };\nclass FloatBox { float value; };\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Class Template:<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>template &lt;typename T&gt;\nclass Box {\nprivate:\n    T item;\npublic:\n    void set(T value) { item = value; }\n    T get() const { return item; }\n};\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Usage:<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Box&lt;int&gt; b1;\nb1.set(100);\n\nBox&lt;string&gt; b2;\nb2.set(\"Apples\");\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Class Template Example<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\ntemplate &lt;class T&gt;\nclass Calculator {\nprivate:\n    T num1, num2;\npublic:\n    Calculator(T a, T b) : num1(a), num2(b) {}\n    T add() { return num1 + num2; }\n    T subtract() { return num1 - num2; }\n};\n\nint main() {\n    Calculator&lt;int&gt; obj1(10, 5);\n    cout &lt;&lt; obj1.add() &lt;&lt; endl;\n\n    Calculator&lt;int&gt; obj2(10.5, 2.2);\n    cout &lt;&lt; obj2.add() &lt;&lt; endl;\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">6. Why Templates Matter<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Reusable code<\/strong>: Write once, use for any type.<\/li>\n\n\n\n<li><strong>Type safety<\/strong>: Compiler handles type correctness.<\/li>\n\n\n\n<li><strong>Performance<\/strong>: Optimized code generated per type.<\/li>\n\n\n\n<li><strong>Foundation of STL<\/strong>: The Standard Template Library uses templates extensively.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to STL (Standard Template Library)<\/h2>\n\n\n\n<p>To manage data efficiently in real-world applications, programmers need ready-made structures such as lists, maps, stacks, and sorting functions. Writing these from scratch every time is time\u2011consuming and error\u2011prone. The <strong>Standard Template Library (STL)<\/strong> provides these tools in a reusable and optimized form.<\/p>\n\n\n\n<p>Here is the student\u2011friendly definition:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>STL (Standard Template Library) is a collection of template-based data structures,\nalgorithms, and iterators that allow efficient storage, processing, and traversal\nof data in C++.\n<\/code><\/pre>\n\n\n\n<p>STL provides the following major components:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Containers:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>vector&lt;T><\/code><\/li>\n\n\n\n<li><code>list&lt;T><\/code><\/li>\n\n\n\n<li><code>queue&lt;T><\/code><\/li>\n\n\n\n<li><code>stack&lt;T><\/code><\/li>\n\n\n\n<li><code>map&lt;Key,Value><\/code><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Algorithms:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>sort()<\/code><\/li>\n\n\n\n<li><code>find()<\/code><\/li>\n\n\n\n<li><code>count()<\/code><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Iterators:<\/h3>\n\n\n\n<p>Generic pointers for containers.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">STL Example: vector<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\nusing namespace std;\n\nint main() {\n    vector&lt;int&gt; numbers;\n    numbers.push_back(10);\n    numbers.push_back(20);\n    numbers.push_back(30);\n\n    for (int x : numbers)\n        cout &lt;&lt; x &lt;&lt; \" \";\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">STL Example: pair&lt;T1,T2&gt;<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\n#include &lt;utility&gt;\nusing namespace std;\n\nint main() {\n    pair&lt;string, int&gt; student;\n    student.first = \"Ali\";\n    student.second = 22;\n    cout &lt;&lt; student.first &lt;&lt; \" is \" &lt;&lt; student.second &lt;&lt; \" years old.\";\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">STL Algorithm Example: sort()<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\nusing namespace std;\n\nint main() {\n    vector&lt;int&gt; data = {4, 1, 9, 2};\n    sort(data.begin(), data.end());\n\n    for (int x : data)\n        cout &lt;&lt; x &lt;&lt; \" \";\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Questions<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Write a function template <code>minValue()<\/code>.<\/li>\n\n\n\n<li>Create a class template <code>Storage&lt;T><\/code>.<\/li>\n\n\n\n<li>Create and print a vector of strings.<\/li>\n\n\n\n<li>Sort a vector of doubles.<\/li>\n<\/ol>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Imagine running a grocery shop. You use different delivery boxes for apples, oranges, and eggs etc. 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 writing a single piece of code that works for multiple data types. Templates enable generic programming, letting the compiler generate functions or classes for different data types automatically. What Are Templates? Template&#8230;<\/p>\n<p class=\"read-more\"><a class=\"btn btn-default\" href=\"https:\/\/afzalbadshah.com\/index.php\/2025\/04\/02\/c-templates-and-standard-template-library-stl-a-complete-beginner-friendly-tutorial\/\"> Read More<span class=\"screen-reader-text\">  Read More<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":17857,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"enabled":false},"version":2}},"categories":[637],"tags":[733,730],"class_list":["post-17825","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oop-with-c","tag-standard-template-library","tag-template"],"aioseo_notices":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2025\/11\/OOP-6.jpg?fit=1920%2C1080&ssl=1","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pf3emP-4Dv","jetpack-related-posts":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/17825","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/comments?post=17825"}],"version-history":[{"count":1,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/17825\/revisions"}],"predecessor-version":[{"id":17859,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/17825\/revisions\/17859"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media\/17857"}],"wp:attachment":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media?parent=17825"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/categories?post=17825"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/tags?post=17825"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}