<?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 smita mandhare on Medium]]></title>
        <description><![CDATA[Stories by smita mandhare on Medium]]></description>
        <link>https://medium.com/@smi.mandhare29?source=rss-c35ccae81f03------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*u-VeqzSbdR09jG6i_kUuhg.jpeg</url>
            <title>Stories by smita mandhare on Medium</title>
            <link>https://medium.com/@smi.mandhare29?source=rss-c35ccae81f03------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:00:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@smi.mandhare29/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[Deep Dive into C++ STL | Part 1 |Containers]]></title>
            <link>https://medium.com/@smi.mandhare29/deep-dive-into-c-stl-part-1-containers-56d3f865a429?source=rss-c35ccae81f03------2</link>
            <guid isPermaLink="false">https://medium.com/p/56d3f865a429</guid>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[stl]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[smita mandhare]]></dc:creator>
            <pubDate>Sun, 31 May 2020 17:23:40 GMT</pubDate>
            <atom:updated>2020-05-31T17:23:40.104Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Hope you are safe and doing great..!!</em></strong></p><p>C++ got lots of additions in C++11, C++14, C++17 and more recently C++20. By now, it is completely different compared to what it was a decade ago. The C++ standard does not only standardize the language, as it needs to be understood by compilers, but it also standardizes the STL (Standard Template Library).</p><p>To go through this article, I am assuming you have hands-on experience with C++ or have worked with at least one Object Oriented Programming Language.</p><p>While developing any application in C++, STL plays an important role. The internet is full of resources to learn STL but most of them are explained with amature examples. They explain how to use STL with simple data types but they don’t go that extra mile to give examples with classes and pointers. In the real world of C++ Application Development, STL is going to be used with classes and pointers only. In this article, you’re gonna learn how to use STL with classes and pointers.</p><p>What?</p><p>Pointers?? 😰</p><p>🏃‍♀️🏃‍♀️🏃‍♀️🏃‍♀</p><p>Wait, wait… don’t run away! 😃</p><p>Pointers are NOT as complicated as they seem to be. Once you start coding with C++, you’ll get used to pointers in no time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*fcTDvWrBBHm3bsSi" /></figure><p>Little Introduction to STL</p><p>Before understanding how STL works with any class object, you must be asking how can map store int or any other class object? Well, there must be some generic code which handles any data type.</p><p>STLs are implemented based on generic template code. Let’s understand it step by step.</p><p>A template is a simple and yet very powerful tool in c++. The simple idea is to pass data types as parameters so that we don’t need to write some code for different data types. C++ provides two types of templates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/0*g2aPJVagLqsLnM5L" /><figcaption>Types of Templates</figcaption></figure><p><strong>typename</strong> indicates data type. Let’s go through the following code to understand the function template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/0*kgR22mPOM_tOOeJO" /></figure><p>STLs are implemented using class templates.Suppose we defined mypair as a new data type.</p><pre>template &lt;class T&gt;<br>class mypair {<br>    T values [2];<br>  public:<br>    mypair (T first, T second)<br>    {<br>      values[0]=first; values[1]=second;<br>    }<br>};</pre><p><strong>mypair</strong> can take any class object.</p><p>As you’ve got some idea on how STL works with any class, now we can dive into its usage in real applications, its time complexity and how it’s stored in memory. But first, let’s look at the main features of STL.</p><p>STL can be divided into 3 main features:</p><h4><strong>1. Containers</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*juiQRn-H1QrpG757" /><figcaption>containers types</figcaption></figure><p><strong>2. Iterators</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*vTIoO2Rn6-TCloIWtjKZPw.png" /><figcaption>Iterators type</figcaption></figure><p><strong>3. Algorithms</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*_X8q7w9PUyTdqN__" /><figcaption>Algorithm types</figcaption></figure><p>In this part our focus will be on <strong>Containers.</strong></p><p>Containers</p><p><em>What is a Container?</em></p><p>“An STL Container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows a great flexibility in the types supported as elements.” — — — <em>cplusplus.com</em></p><h3>A. Sequential Container</h3><p><em>Why the name Sequence?</em></p><p>Sequential containers implement data structures which can be accessed sequentially.</p><p>Let’s look into each Sequential Container <em>sequentially. </em>😎</p><h3>1. Array</h3><h3>Declaration:</h3><p>array&lt;datatype, size&gt; arrayName;</p><h3>Initialization:</h3><p>array&lt;int,5&gt; marks = {87, 98, 70, 90, 100};</p><p><strong>Size of an array is Fixed.</strong></p><h3>Arrays are already there in C++, then why is it added in STL?</h3><ul><li>C-style arrays don’t know their own size. But Array Containers know their own size. So when passing an array to a function, we don’t need to pass it’s size unlike we do in C-type arrays.</li><li>C-style arrays worked and entirely accessed by pointers whereas Array Containers are not.</li><li>Array Containers have more inbuilt functions than C-style arrays. So these are more efficient.</li></ul><p>Let’s implement it in class.</p><p><em>Problem statement: There is a library of school staff consisting of 100 persons which is constant and not going to change. Write code where the system can show which person has numbers of a specific book category. Here only consider learning the array concept, as code is written instantly, not a standard code like in an application. Here we’re using the index of the array as the id of the person.</em></p><pre>#include &lt;iostream&gt;<br>#include &lt;array&gt;</pre><pre>using namespace std;</pre><pre>class library<br>{<br>    public:<br>    <br>    library()<br>    {<br>        comicBooks = 0;<br>        hostoricalBooks = 0;<br>        scienceBooks = 0;<br>    }<br>    <br>    library(int comic,int histroy,int science)<br>    {<br>     comicBooks = comic;<br>     hostoricalBooks = histroy;<br>     scienceBooks = science;<br>    }<br>    <br>    ~library()<br>    {<br>        <br>    }<br>       <br>    private:<br>    int comicBooks;<br>    int hostoricalBooks;<br>    int scienceBooks;<br>    <br>};</pre><pre>int main()<br>{<br> <br> array &lt;library, 100&gt; staff; //all are initialized as zero initially<br> library person0(1,2,2);<br> staff[0] = person0;<br> cout &lt;&lt; staff[0];<br> library person1(1,0,1);<br> staff[1] = person1<br> library person5(3,1,1);<br> staff[5] = person5;<br> <br>}</pre><p>Here cout &lt;&lt; staff[0] will give error because &lt;&lt; operator is not defined. So below code is required as a member function.</p><pre>    friend ostream &amp;operator&lt;&lt;(ostream &amp;out, const library &amp;obj)<br>    {<br>        cout &lt;&lt; obj.comicBooks;<br>        cout &lt;&lt; obj.hostoricalBooks;<br>        cout &lt;&lt; obj.scienceBooks;        <br>    }</pre><h3>2. Vector</h3><ul><li>Vectors are dynamically sized arrays</li><li>Always prefer vectors over raw arrays</li></ul><p><strong>Declaration:</strong></p><p><em>To declare an empty int array:</em></p><p>Vector &lt;int&gt; a</p><p><em>To declare a zero-initialized double “array” of size 50:</em></p><p>Vector &lt;double&gt; b(50)</p><p><em>To declare an int “array” of size n, with element initialized to 10:</em></p><p>Vector &lt;int&gt; (n,10)</p><p>- <em>Unlike arrays, vectors are aware of their size.</em></p><p>Vector &lt;int&gt; v1{1,4,2,8}</p><p>Cout &lt;&lt; v1.size(); // 4</p><p>- <em>When there is no capacity left, an additional memory of size 2 times the original capacity is allocated. The capacity is now doubled and the data is moved to the newly allocated memory. Push_back is used to append an element at the end in a vector.</em></p><p>v1.push_back(5);</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*dbj414Nq-b-Alp3A" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/0*Gy1xOVu7RGVf01AR" /></figure><p>Size indicates numbers in vectors and capacity is how much can be stored. Here now the vector size will increase from 4 to 8. (2n times)</p><h3>How to traverse through a vector?</h3><p>Suppose vector is v2 of type int:</p><p>Vector &lt;int&gt; v2 = {1,2,3,4,5}</p><ol><li>Using indices:</li></ol><pre>for(int i =0; i &lt;v2.size();i++)<br>  Cout &lt;&lt; v2[i] &lt;&lt; endl;</pre><p>2. Using iterator // will discuss later</p><pre>for(vector&lt;int&gt;iterator::it = v2.begin(); it !=v2.end();it++) <br>   Cout &lt;&lt; *it &lt;&lt; endl;</pre><p>3. Using ranged-based loop</p><pre>for(int x: v2)<br>  Cout &lt;&lt; x &lt;&lt; endl;</pre><p>Vector has it’s own public member functions to utilize it.</p><p>Let’s see how it is use with classes Inventory is class with 3 private members:</p><ol><li>Size — Recently we has used size which gives numbers of elements in container</li><li>Capacity — returns size allocated to vector</li><li>Push_back — add element at end of vector</li></ol><p><em>Problem :</em><strong><em>inventory</em></strong><em> has 3 memory of different branch shoes, bandminton, and playerId. shop1 will have different brands of above things. Numbers of different brand may be change at run time.</em></p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;</pre><pre>using namespace std;</pre><pre>class inventory<br>{<br>    public:<br>    inventory(int mshoes, int mbandminton, int mplayerId)<br>    {<br>        shoes = mshoes;<br>        bandminton = mbandminton;<br>        playerId = mplayerId;<br>    }</pre><pre>    ~inventory()<br>    {<br>        <br>    }<br>    <br>    void SetAllParam(int shoes,int bandminton, int playerId)<br>    {<br>        this-&gt;shoes = shoes;<br>        this-&gt;bandminton = bandminton;<br>        this-&gt;playerId = playerId;<br>    }</pre><pre>    int getShoes()<br>    {<br>        return shoes;<br>    }<br>    <br>    int getBandminton()<br>    {<br>        return bandminton;<br>    }<br>    <br>    int getPlayerId()<br>    {<br>        return playerId;<br>    }<br>    <br>    private:<br>    int shoes;<br>    int bandminton;<br>    int playerId;<br>};</pre><pre>int main()<br> {<br>    inventory object1(0,0,0); //constr call<br>    object1.SetAllParam(12,76,90); // function call<br>    inventory object2(99,80,70); //const call<br>    inventory object3(90,80,60);</pre><pre>   //Initialise vector object push_back is fun use to add element in vector</pre><pre>     vector &lt;inventory&gt; shop1;<br>     shop1.push_back(object1);<br>     shop1.push_back(object2);</pre><pre>    //to store pointer vector</pre><pre>    inventory *pionterToObject3;<br>    pionterToObject3 = &amp;object3;<br>    shop2.push_back(pionterToObject3);</pre><pre>   /*this is one way to access vector will discuss about this later       here it will not work as no overloading of operator&lt;&lt; <br>    <br>    for (auto it : shop1) <br>    cout &lt;&lt; it;<br>    */<br> }</pre><pre>//To support &lt;&lt; operator we need to write a definition for the same.<br> <br>    friend ostream&amp; operator &lt;&lt; (ostream &amp;out, const inventory &amp;obj)   <br>    {<br>     out &lt;&lt; obj.shoes;<br>     out &lt;&lt; obj.bandminton;<br>     out &lt;&lt; obj.playerId;<br>    }</pre><p>How does vector works internally?</p><p>std::vector allocates a memory on heap and store all its elements in contiguous memory location.</p><p>But what if memory it allocated initially is completely filled?</p><p>For example, let’s create a vector of int i.e. std::vector&lt;int&gt; . Now suppose it’s initial capacity is to store 10 elements, but in our application we want to store 15 elements in it. Then what will happen when we will insert 11th element?</p><p>When std::vector’s internal memory completely finishes then it increases the size of its memory. To do that it performs following steps,</p><p>1.) It will allocate a bigger chunk of memory on heap i.e. almost double the size of previously allocated.</p><p>2.) Then it copies all the elements from old memory location to new one. Yes it copies them, so in case our elements are user defined objects then their copy constructor will be called. Which makes this step quite heavy in terms of speed.</p><p>3.) Then after successful copying it deletes the old memory.</p><p>You can check the current capacity of vector i.e. how much elements it can store in current allocated memory using capacity() member function.</p><p>Time Complexity:</p><p>If we create a new double sized array whenever current array becomes full (or it is about to become full), and copy current elements to new double sized array, we get amortized time complexity as O(1). So a particular insert operation may be costly, but overall time complexity remains O(1). Since erasing an element requires moving other elements (to ensure random access), time complexity of erase is O(1)</p><h3><strong>3. List</strong></h3><p>List is a container that supports constant time insertion and removal of elements from anywhere in the container. Fast random access is not supported. It is usually implemented as a doubly-linked list. Doubly linked lists can store each of the elements, they contain in different and unrelated storage locations. The ordering is kept internally by the association to each element of a link to the element preceding it and a link to the element following it.</p><p>They are very similar to <a href="http://www.cplusplus.com/forward_list">forward_list</a>: The main difference being that <a href="http://www.cplusplus.com/forward_list">forward_list</a> objects are single-linked lists, and thus they can only be iterated forwards, in exchange for being somewhat smaller and more efficient.</p><p>Compared to other base standard sequence containers (<a href="http://www.cplusplus.com/array">array</a>, <a href="http://www.cplusplus.com/vector">vector</a> and <a href="http://www.cplusplus.com/deque">deque</a>), lists perform generally better in inserting, extracting and moving elements in any position within the container for which an iterator has already been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms.</p><p>The main drawback of lists and <a href="http://www.cplusplus.com/forward_list">forward_list</a>s compared to these other sequence containers is that they lack direct access to the elements by their position; For example, to access the sixth element in a list, one has to iterate from a known position (like the beginning or the end) to that position, which takes linear time in the distance between these. They also consume some extra memory to keep the linking information associated to each element (which may be an important factor for large lists of small-sized elemets).</p><p>can conclude below points:</p><ul><li>Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by their position in this sequence.</li><li>Implements bidirectional linked list</li><li>Each element keeps information on how to locate the next and the previous elements, allowing constant time insert and erase operations before or after a specific element (even of entire ranges), but no direct random access.</li><li>The container uses an allocator object to dynamically handle its storage needs.</li><li>syntax : list &lt;dataType&gt; obj;</li></ul><pre>std::list&lt;int&gt; l;</pre><pre>std::list&lt;int&gt; l{1,2,3};<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*YX3Xtr9EuX2k8ZCpzXz8Gg.png" /></figure><p>Elements of the list can be scattered in the different chunks of memory. Container stores the necessary information to allow sequential access to its data.</p><p>C++ Lists can shrink or expand as needed from both ends at run time. The storage requirement is fulfilled automatically by the internal allocator.</p><p>Zero-sized lists are also valid. In that case <strong>list.begin()</strong> and <strong>list.end()</strong> points to the same location. But the behavior of calling front() or back() is undefined.</p><h3>std::list doesn’t have operator []</h3><p>std::list does not have random access operator [] because std::list internally store elements in doubly linked list. So, to access an element at nth location we need to iterate one by one from beginning to nth element. So, its complexity will be O(n).</p><p>Suppose we have a list of strings i.e.</p><pre>std::list&lt;std::string&gt; listOfStrs = { &quot;First&quot;, &quot;Sec&quot;,<br>&quot;Third&quot;, &quot;Fourth&quot;,<br>&quot;Fifth&quot;, &quot;Sixth&quot;<br>};</pre><p>Now lets see how to access element at 3rd position from list using 2 different techniques.</p><pre>template &lt;class InputIterator, class Distance&gt;<br>void advance (InputIterator&amp; it, Distance n);</pre><pre>// Create iterator pointing to first element<br>std::list&lt;std::string&gt;::iterator it = listOfStrs.begin();<br>// Advance the iterator by 2 positions,<br>std::advance(it, 2);</pre><p>As iterator <strong>it</strong> was already pointing to first element, therefore we need to advance it by 2 to point it to 3rd position.</p><p>Complexity of std::advance for std::list is O(n) because it needs to iterate one by one from beginning to nth position.</p><p>In C++11 another algorithm has been introduced i.e std::next().</p><h3>Accessing nth element in std::list using std::next()</h3><p>std::next() is introduced in C++11. It accepts an iterator and position to be advanced. It does not modify the passed iterator, but uses it to create a new iterator pointing to nth -1 position from given iterator and returns it.</p><p>Lets see how to access element at 3rd position by std::next()</p><p>auto it1 = std::next(listOfStrs.begin(), 2);</p><pre>std::list&lt;int&gt; integer_list;<br><br>integer_list.push_front(1);<br>integer_list.push_front(2);</pre><p>Problem Statement: Write a program where one element has port and priority, another sub-element has host and weight. write a code where, sub-system dynamically add element.</p><pre>class TheElement<br>{<br>    <br> public:<br> TheElement(){mport = 0; mpriority = 0;}<br> TheElement(int port, bool priority) { mport = port; mpriority =   false;}<br>~TheElement() { }<br>    <br> private:<br> int mport;<br> bool  mpriority;     <br>};</pre><pre>class SubElement<br>{<br>  public:<br>  <br>  SubElement() {mhost = 0; mweight = 0;}<br>  ~SubElement() { }<br>  int GetWeight() {return mweight;}<br>  int GetHost() {return mhost;}<br>  list&lt;TheElement&gt; mTheElements;<br>  <br>  <br>  private:<br>  int mhost;<br>  int mweight;<br>};</pre><pre>int main()<br> {<br>     TheElement objectOfTheElement;<br>     SubElement objectOfSubElement;<br>     objectOfSubElement.mTheElements.push_back(objectOfTheElement);<br>    <br> }</pre><h3><strong>4. Deque:</strong></h3><p>Deque is a double ended queue container that provides insertion and deletion at both ends i.e. front and back with<br>high performance unlike vector that provides high performance insertion at end i.e. back only.</p><p>Also it provides random access to elements just like a vector. Although one can insert an element in between other elements in dequeue with insert() function, but its performance will not be good just like vector.</p><p>Inserting an element in front of deque push_front is used. push_back is used to insert element at end. pop_front is used to remove element from front and pop_back used to remove from back of queue.</p><p>How deque is work internally?</p><p>Now a question rises how high deque is able to give good performance for insertion and deletion at both ends?<br>To know the answer we need to know little internal implementation of dequeue.</p><p>A deque is generally implemented as a collection of memory blocks. These memory blocks contains the elements at contiguous locations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*vS8z1Rbv6pL_cTff.png" /></figure><p>When we create a deque object it internally allocates a memory block to store the elements at contigious location.</p><ul><li>When we insert an element in end it stores that in allocated memory block untill it gets filled and when this memory block gets filled with elements then it allocates a new memory block and links it with the end of previous memory block. Now further inserted elements in the back are stored in this new memory block.</li><li>When we insert an element in front it allocates a new memory block and links it with the front of previous memory block. Now further inserted elements in the front are stored in this new memory block unless it gets filled.</li><li>Consider deque as a linked list of vectors i.e. each node of this linked list is a memory block that store elements at contiguous memory location and each of the memory block node is linked with its previous and next memory block node.</li></ul><p>Therefore, insertion at front is fast as compared to vector because it doesn’t need the elements to shift by 1 in current memory block to make space at front. It just checks if any space is left at left of first element in current memory block, if not then allocates a new memory block.</p><p><em>Problem Statement: Write a program to push 2 elements from the front end and 2 elements from the back end and print the deque.</em></p><pre>#include &lt;iostream&gt;<br>#include &lt;deque&gt;</pre><pre>using namespace std;</pre><pre>void showdata(deque&lt;int&gt; deque1)<br>{<br>  deque&lt;int&gt;::iterator iterator_1;<br>  for (iterator_1 = deque1.begin(); iterator_1 != deque1.end(); ++iterator_1)<br>    cout &lt;&lt; &quot;\t&quot; &lt;&lt; *iterator_1;<br>  cout &lt;&lt; &quot;\n&quot;;<br>}</pre><pre>int main()<br>{<br>  deque&lt;int&gt; myqueue;<br>  myqueue.push_front(230); // getting data from front<br>  myqueue.push_front(240); // getting data from front<br>  myqueue.push_back(250);  // getting data from back<br>  myqueue.push_back(260);  // getting data from back<br>  cout &lt;&lt; &quot;Deque elements are: &quot;;<br>  showdata(myqueue);</pre><pre>return (0);<br>}</pre><h3><strong>B. Associative Containers</strong></h3><p>why name associative?</p><p>because they associate <em>keys</em> with <em>values</em>. Well, at least <strong>map</strong>s and <strong>multimap</strong>s associate keys with values, but you can look at a <strong>set</strong> as a <strong>map</strong> that has no values, only keys.</p><h3><strong>1. Set</strong></h3><p>Set is a container implemented in C++ language in STL and has a concept similar to how set is defined in mathematics. The facts that separates set from the other containers is that is it contains only the <strong>distinct elements</strong> and elements can be traversed in sorted order. Having the strong hold on sets is useful in competitive programming and solving algorithmic problems.</p><ul><li>It’s doesn’t allow duplicate elements i.e. it only contains unique elements.</li><li>Std::set can contain element of any specified type in template argument i.e.</li></ul><pre>std::set&lt;int&gt; // contains only int elements.<br>class Sample;<br>std::set&lt;Sample&gt; // contains only Sample class objects.</pre><ul><li>std::set internally store elements in balanced binary tree.</li><li>By default std::set uses the operator &lt; for comparing two elements and but if user passes the external sorting criteria i.e. comparator then it uses that instead of default operator &lt;.</li><li>std::set will keep the inserted elements in sorted order based on the assigned sorting criteria i.e. either by default criteria operator &lt; or by passed comparator (if passed).</li></ul><p>public member function :</p><p>std::<a href="http://www.cplusplus.com/reference/set/set/">set</a>::key_comp</p><pre>key_compare key_comp() const;</pre><p><strong>Return comparison object</strong></p><p>Returns a copy of the <em>comparison object</em> used by the container.</p><p>By default, this is a <a href="http://www.cplusplus.com/less">less</a> object, which returns the same as operator&lt;.</p><p>This object determines the order of the elements in the container: it is a function pointer or a function object that takes two arguments of the same type as the container elements, and returns true if the first argument is considered to go before the second in the <em>strict weak ordering</em> it defines, and false otherwise.</p><p>Two elements of a <a href="http://www.cplusplus.com/set">set</a> are considered equivalent if key_comp returns false reflexively (i.e., no matter the order in which the elements are passed as arguments).</p><p>In <a href="http://www.cplusplus.com/set">set</a> containers, the keys to sort the elements are the values themselves, therefore key_comp and its sibling member function <a href="http://www.cplusplus.com/set::value_comp">value_comp</a> are equivalent.</p><h3>Return value</h3><p>The comparison object.<br>Member type key_compare is the type of the <em>comparison object</em> associated to the container, defined in <a href="http://www.cplusplus.com/set">set</a> as an alias of its second template parameter (Compare).</p><pre>int main ()<br>{<br>  std::set&lt;int&gt; myset;<br>  int highest;<br>  std::set&lt;int&gt;::key_compare mycomp = myset.key_comp();</pre><pre>  for (int i=0; i&lt;=5; i++) myset.insert(i);<br>    <br>  std::cout &lt;&lt; &quot;myset contains:&quot;;<br>  highest=*myset.rbegin();</pre><pre>  std::set&lt;int&gt;::iterator it=myset.begin();<br>  do {<br>    std::cout &lt;&lt; &#39; &#39; &lt;&lt; *it;<br>  } while ( mycomp(*(++it),highest) );</pre><pre>  std::cout &lt;&lt; &#39;\n&#39;;<br>  return 0;<br>}</pre><p><strong>Inserting element into set:</strong></p><p>There are different ways we can insert elements into set.</p><p><strong>Note:</strong> In any method below when we insert an element into set it automatically inserted at proper position based on ascending sorted order.</p><p><strong>Method 1:</strong> Insert directly by passing element. <strong>setName.insert(element);</strong></p><p><strong>Method 2:</strong> Using iterator. This returns iterator at inserted position. <strong>setName.insert (iterator,value)</strong></p><p><strong>Method 3:</strong> Copying from another container.</p><pre>#include&lt;iostream&gt;</pre><pre>#include&lt;set&gt;</pre><pre><strong>using</strong> <strong>namespace</strong> std;</pre><pre><strong>int</strong> main(){</pre><pre>set&lt;<strong>int</strong>&gt; s1; <em>// declaring a set</em></pre><pre>set&lt;<strong>int</strong>&gt; :: iterator it; <em>// iterator for set</em></pre><pre><strong>for</strong>(<strong>int</strong> i=0;i&lt;5;i++){</pre><pre>s1.insert(i*10); <em>// inserting using Method1</em></pre><pre>}<br>it= s1.begin();</pre><pre>s1.insert(it,99); <em>// inserting using Method2</em></pre><pre><strong>int</strong> ary[]= { 23, 34, 45, 56};</pre><pre>s1.insert(ary, ary+4); <em>// inserting using Method3</em></pre><pre><em>//checking by printing</em></pre><pre><strong>for</strong>(it= s1.begin(); it!=s1.<strong>end</strong>(); it++)</pre><pre><strong>cout</strong> &lt;&lt; *it &lt;&lt; &quot; &quot;;</pre><pre><em>// We can observe that output will be print in sorted order. That is the property of set</em></pre><pre><strong>return</strong> 0;</pre><pre>}</pre><p>Can you guess output of following code</p><pre>#include&lt;set&gt;<br>#include&lt;string&gt;<br>#include&lt;iostream&gt;</pre><pre>using namespace std;</pre><pre>class Marks<br>{<br>    public:<br>    Marks(int math, int science, int history)<br>    {<br>      this-&gt;math = math ;<br>      this-&gt;science = science ; <br>      this-&gt;history = history;<br>    }<br>    ~Marks(){}<br>    private:<br>    int math;<br>    int science;<br>    int history;<br>};</pre><pre>int main()<br>{<br>    Marks student1(90,80,70);<br>    set &lt;Marks&gt; students;<br>    students.insert(student1);<br> return 0;<br>}</pre><p>It will give compilation Error. How???</p><p>let’s rewind definition of set. It has distict elements hence no duplicate allowed and it is in sorted form. For sorting it has operator &lt; overloaded operator. here it is not defined in class. hence program will give following error:</p><pre>main.cpp:23:29&lt;/span&gt;:   required from here<br>/usr/include/c++/6/bits/stl_function.h:386:20: error: no match for ‘operator&lt;’ (operand types are ‘const Marks’ and ‘const Marks’)<br>       { return __x &lt; __y; }<br>                ~~~~^~~~~</pre><p>let’s add defination of &lt; operator in class as below:</p><pre>#include&lt;set&gt;<br>#include&lt;string&gt;<br>#include&lt;iostream&gt;</pre><pre>using namespace std;</pre><pre>class Marks<br>{<br>    public:<br>    <br>    Marks(int id, int math, int science, int history)<br>    {this-&gt;id = id;this-&gt;math = math; this-&gt;science = science; this-&gt;history = history;}<br>    ~Marks(){}<br> <br>     bool operator &lt;(const Marks &amp;object2) const<br>    {<br>        if(this-&gt;id != object2.id)<br>       return (this-&gt;math &lt;= object2.math || this-&gt;science &lt;= object2.science || this-&gt;history &lt;= history);<br>       else<br>       return false;<br>    }<br>    friend ostream &amp;operator&lt;&lt;(const ostream &amp;out, const Marks &amp;obj)<br>    {<br>        cout &lt;&lt; &quot;id &quot; &lt;&lt; obj.id &lt;&lt; endl;<br>        cout &lt;&lt; &quot;math &quot; &lt;&lt; obj.math &lt;&lt; endl;<br>        cout &lt;&lt; &quot;science &quot; &lt;&lt; obj.science &lt;&lt; endl;<br>        cout &lt;&lt; &quot;history &quot; &lt;&lt; obj.history &lt;&lt; endl;<br>    }<br>    private:<br>    int id;<br>    int math;<br>    int science;<br>    int history;<br>};</pre><pre>int main()<br>{<br>    Marks student1(1,99,88,70),student2(2,90,80,88);<br>    Marks student3(3,99,80,56);<br>    Marks student4(3,11,11,11);<br>    set &lt;Marks&gt; students;<br>    students.insert(student1);<br>    students.insert(student2);<br>    students.insert(student3);<br>    <br>    for (auto it : students) { <br>         cout &lt;&lt; it;<br>    }<br>    <br> return 0;<br>}</pre><p>There is another set called <strong>unorderd_set</strong> where duplicate keys are not allowed but it is not in sorted.</p><h3><strong>2. Multiset:</strong></h3><p>Multisets are a type of associative containers similar to set, with an exception that multiple elements can have same values.</p><p>Internally, the elements in a multiset are always sorted following a specific <em>strict weak ordering</em> criterion indicated by its internal <a href="http://www.cplusplus.com/multimap::key_comp">comparison object</a> (of type Compare).</p><p>multiset containers are generally slower than <a href="http://www.cplusplus.com/unordered_multiset">unordered_multiset</a> containers to access individual elements by their <em>key</em>, but they allow the direct iteration on subsets based on their order.</p><p>Multisets are typically implemented as <em>binary search trees</em>.</p><pre>#include &lt;iostream&gt;<br>#include &lt;set&gt;</pre><pre>using namespace std;</pre><pre>int main()<br>{<br>   // empty multiset container <br>   // multiset &lt;int, greater &lt;int&gt; &gt; gquiz1;   <br>   multiset &lt;int&gt; obj1;<br>   <br>   // insert elements in random order <br>   obj1.insert(40);<br>   obj1.insert(30);<br>   obj1.insert(60);<br>   obj1.insert(20);<br>   obj1.insert(50);<br>   obj1.insert(30);<br>   <br>    // printing multiset  <br>    multiset &lt;int&gt; :: iterator itr; <br>    <br>    cout &lt;&lt; &quot;\nThe multiset is : &quot;; <br>    for (itr = obj1.begin(); itr != obj1.end(); ++itr) <br>    { <br>        cout &lt;&lt; &#39;\t&#39; &lt;&lt; *itr; <br>    } <br>    cout &lt;&lt; endl; <br>  <br>    // assigning the elements from obj1 to obj2 <br>    multiset &lt;int&gt; obj2(obj1.begin(), obj1.end()); <br>  <br>    // print all elements of the multiset obj2 <br>    cout &lt;&lt; &quot;\nThe multiset obj2 after assign from obj1 is : &quot;; <br>    for (itr = obj2.begin(); itr != obj2.end(); ++itr) <br>    { <br>        cout &lt;&lt; &#39;\t&#39; &lt;&lt; *itr; <br>    } <br>    cout &lt;&lt; endl; <br>  <br>    // remove all elements up to element with value 30 in obj2 <br>    cout &lt;&lt; &quot;\nobj2 after removal of elements less than 30 : &quot;; <br>    obj2.erase(obj2.begin(), obj2.find(30)); <br>    for (itr = obj2.begin(); itr != obj2.end(); ++itr) <br>    { <br>        cout &lt;&lt; &#39;\t&#39; &lt;&lt; *itr; <br>    } <br>    <br>    // remove all elements with value 50 in obj2 <br>    int num; <br>    num = obj2.erase(50); <br>    cout &lt;&lt; &quot;\nobj2.erase(50) : &quot;; <br>    cout &lt;&lt; num &lt;&lt; &quot; removed \t&quot; ; <br>    for (itr = obj2.begin(); itr != obj2.end(); ++itr) <br>    { <br>        cout &lt;&lt; &#39;\t&#39; &lt;&lt; *itr; <br>    } <br>  <br>    cout &lt;&lt; endl; <br>   <br>}</pre><p>There is another set called <strong>unorderd_multiset</strong> where duplicate keys are allowed but it is not in sorted.</p><h3><strong>C. Adapter container</strong></h3><p>why name adapter container?</p><p>Each of these “adaptors container ” is constructed by taking one of the sequential containers given above and “adapting” (restricting/modifying) its interface to provide the desired behavior.</p><h3><strong>1. Stack</strong></h3><p>Being in software development, we are pretty known to stack. It is same as stack data structure.</p><p>It is a simple data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the <strong>top</strong> of the stack and the only element that can be removed is the element that is at the top of the stack, just like a pile of objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*ngnTjXxOM6eq3SrcKlcx4g.png" /><figcaption>stack mechanism</figcaption></figure><p><strong>stack</strong>s are implemented as <em>container adaptors</em>, which are classes that use an encapsulated object of a specific container class as its <em>underlying container</em>, providing a specific set of member functions to access its elements. Elements are <em>pushed</em>/<em>popped</em> from the <em>“back”</em> of the specific container, which is known as the <em>top</em> of the stack.</p><p>The underlying container may be any of the standard container class templates or some other specifically designed container class. The container shall support the following operations:</p><ul><li>empty</li><li>size</li><li>back</li><li>push_back</li><li>pop_back</li></ul><p>The standard container classes <a href="http://www.cplusplus.com/vector">vector</a>, <a href="http://www.cplusplus.com/deque">deque</a> and <a href="http://www.cplusplus.com/list">list</a> fulfill these requirements. By default, if no container class is specified for a particular stack class instantiation, the standard container <a href="http://www.cplusplus.com/deque">deque</a> is used.</p><p><em>Problem Statement: scheduler has to be defined where there is numbers of tasks with equal priority. top most task will be served first and will be removed.</em></p><pre>#include &lt;iostream&gt;<br>#include &lt;stack&gt;</pre><pre>using namespace std;</pre><pre>class scheduler<br>{<br>    public:<br>    // all public elements setters and getters<br>    private:<br>    // all class members</pre><pre>};<br>      <br>int main ()<br>{<br>   scheduler task1,task2,task3;<br>   stack&lt;scheduler&gt; schedulerManager; <br>    <br>    //all tasks are added to stack one by one depending on time creation.<br>    <br>    schedulerManager.push(task1);<br>    schedulerManager.push(task2);<br>    schedulerManager.push(task3);<br>    <br>    //top most task will be serve first it will be removed first    from schedulerManager<br>    <br>    schedulerManager.pop();<br>    cout &lt;&lt; schedulerManager.size();  // prints 2, as there are 2elements in <br>}</pre><h3><strong>2. Queue</strong></h3><p>The std::queue class is a container adapter that gives the programmer the functionality of a queue - specifically, a FIFO (first-in, first-out) data structure.</p><p>The class template acts as a wrapper to the underlying container — only a specific set of functions is provided. The queue pushes the elements on the back of the underlying container and pops them from the front.</p><p>Taking is same example which we are learned from engineering. 😜</p><p>If you stand in a queue at a grocery store (or anywhere else), the first customer in the queue will be served, and then the next, and so on.</p><p>How queue is implemented?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*C-pvOUoDYe9nLuQwgJ_C7A.png" /></figure><p>There is good example on <a href="https://www.techiedelight.com/">https://www.techiedelight.com/</a> related to queue. Below code is taken from the same:</p><pre>#include &lt;iostream&gt;<br>#include &lt;cstdlib&gt;<br>using namespace std;</pre><pre>// define default capacity of the queue<br>#define SIZE 10</pre><pre>// Class for queue<br>class queue<br>{<br> int *arr;  // array to store queue elements<br> int capacity; // maximum capacity of the queue<br> int front;  // front points to front element in the queue (if any)<br> int rear;  // rear points to last element in the queue<br> int count;  // current size of the queue</pre><pre>public:<br> queue(int size = SIZE);  // constructor<br> ~queue();       // destructor</pre><pre>void dequeue();<br> void enqueue(int x);<br> int peek();<br> int size();<br> bool isEmpty();<br> bool isFull();<br>};</pre><pre>// Constructor to initialize queue<br>queue::queue(int size)<br>{<br> arr = new int[size];<br> capacity = size;<br> front = 0;<br> rear = -1;<br> count = 0;<br>}</pre><pre>// Destructor to free memory allocated to the queue<br>queue::~queue()<br>{<br> delete arr;<br>}</pre><pre>// Utility function to remove front element from the queue<br>void queue::dequeue()<br>{<br> // check for queue underflow<br> if (isEmpty())<br> {<br>  cout &lt;&lt; &quot;UnderFlow\nProgram Terminated\n&quot;;<br>  exit(EXIT_FAILURE);<br> }</pre><pre>cout &lt;&lt; &quot;Removing &quot; &lt;&lt; arr[front] &lt;&lt; &#39;\n&#39;;</pre><pre>front = (front + 1) % capacity;<br> count--;<br>}</pre><pre>// Utility function to add an item to the queue<br>void queue::enqueue(int item)<br>{<br> // check for queue overflow<br> if (isFull())<br> {<br>  cout &lt;&lt; &quot;OverFlow\nProgram Terminated\n&quot;;<br>  exit(EXIT_FAILURE);<br> }</pre><pre>cout &lt;&lt; &quot;Inserting &quot; &lt;&lt; item &lt;&lt; &#39;\n&#39;;</pre><pre>rear = (rear + 1) % capacity;<br> arr[rear] = item;<br> count++;<br>}</pre><pre>// Utility function to return front element in the queue<br>int queue::peek()<br>{<br> if (isEmpty())<br> {<br>  cout &lt;&lt; &quot;UnderFlow\nProgram Terminated\n&quot;;<br>  exit(EXIT_FAILURE);<br> }<br> return arr[front];<br>}</pre><pre>// Utility function to return the size of the queue<br>int queue::size()<br>{<br> return count;<br>}</pre><pre>// Utility function to check if the queue is empty or not<br>bool queue::isEmpty()<br>{<br> return (size() == 0);<br>}</pre><pre>// Utility function to check if the queue is full or not<br>bool queue::isFull()<br>{<br> return (size() == capacity);<br>}</pre><pre>// main function<br>int main()<br>{<br> // create a queue of capacity 5<br> queue q(5);</pre><pre>q.enqueue(1);<br> q.enqueue(2);<br> q.enqueue(3);<br> <br> cout &lt;&lt; &quot;Front element is: &quot; &lt;&lt; q.peek() &lt;&lt; endl;<br> q.dequeue();<br> <br> q.enqueue(4);</pre><pre>cout &lt;&lt; &quot;Queue size is &quot; &lt;&lt; q.size() &lt;&lt; endl;</pre><pre>q.dequeue();<br> q.dequeue();<br> q.dequeue();<br> <br> if (q.isEmpty())<br>  cout &lt;&lt; &quot;Queue Is Empty\n&quot;;<br> else<br>  cout &lt;&lt; &quot;Queue Is Not Empty\n&quot;;</pre><pre>return 0;<br>}</pre><h3><strong>3. Priority-Queue</strong></h3><p>Let’s take same example as above queue.</p><p>In a priority queue, apart from the FIFO characteristics, certain customers (or elements in a queue) might have a higher priority, and they might receive immediate service irrespective of their location in the queue.</p><p>Priority Queue is an extension of <a href="http://quiz.geeksforgeeks.org/queue-set-1introduction-and-array-implementation/">queue </a>with following properties.</p><ol><li>Every item has a priority associated with it.</li><li>An element with high priority is dequeued before an element with low priority.</li><li>If two elements have the same priority, they are served according to their order in the queue.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*J2Xzfkx0ejtkjoBmErZUdw.png" /></figure><p>A typical priority queue supports following operations.<br><strong>insert(item, priority): </strong>Inserts an item with given priority.<br><strong>getHighestPriority():</strong> Returns the highest priority item.<br><strong>deleteHighestPriority(): </strong>Removes the highest priority item.</p><h3>How does priority queue differ from a queue?</h3><p>In a queue, the <strong>first-in-first-out rule</strong> is implemented whereas, in a priority queue, the values are removed <strong>on the basis of priority</strong>. The element with the highest priority is removed first.</p><h3>The link between heaps and priority queues</h3><p>When reading about priority queues, didn’t their ability to retrieve the largest element reminded you of something?</p><p>Heaps, of course!</p><p>Indeed, in heaps basics we saw that they offer an easy access to the largest elements, by positioning it at their root.</p><p>In fact, the relationship between heaps and priority queues is even closer than that: <strong>heaps are an implementation of priority queues</strong>.</p><p>Indeed, in a heap we can add data, and access and remove the largest element, so they can implement the interface of a priority queue. Let’s see this in more details.</p><p>Let’s consider the following heap (implemented as an array):</p><pre>std::vector&lt;double&gt; numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};</pre><pre>std::make_heap(begin(numbers), end(numbers));</pre><p>Let’s see how to perform the main functions of the interface of a priority queue with the STL algorithms on heaps.</p><h4>Adding an element</h4><p>In a priority queue we need to be able to add an element with the push method.</p><p>Let’s add the new element 4.12. Here is how to do it by using the STL algorithms on heap:</p><pre>numbers.push_back(4.12);<br>std::push_heap(begin(numbers), end(numbers));</pre><h4>Accessing the largest element</h4><p>In a priority queue, we need to access the largest element with the top method. It is located at the beginning of the array and can be accessed in constant time with:</p><pre>numbers.front()</pre><h4>Removing the largest element</h4><p>Finally, a priority queue needs to be able to remove its largest element with its pop method. The algorithm pop_heap moves the first element of the array to its end and rearranges the other elements into a heap:</p><pre>std::pop_heap(begin(numbers), end(numbers)); // 9 is at the end<br>numbers.pop_back(); // 9 is gone, 8 is the new top</pre><p>To sum this all up:</p><p>Priority queues can be implemented by heaps and heaps can be implemented by arrays.</p><h3><strong>Time Complexities of all containers are as below:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*fj37EW7EQ5SmD5o2hNQTeA.png" /></figure><p>References:</p><p><a href="http://www.cplusplus.com/doc/oldtutorial/templates/">http://www.cplusplus.com</a><br><a href="https://discourse-production.oss-cn-shanghai.aliyuncs.com/original/3X/c/e/ce2e1fe51865660aaa835bd2674c1920e49f4c82.pdf">https://discourse-production.oss-cnshanghai.aliyuncs.com/original/3X/c/e/ce2e1fe51865660aaa835bd2674c1920e49f4c82.pdf</a><br><a href="https://www.dre.vanderbilt.edu/~schmidt/PDF/STL.pdf">https://www.dre.vanderbilt.ed</a>u<br><a href="http://assets.hkoi.org/training2017/cppstl.pdf">http://assets.hkoi.org/training2017/cppstl.pdf</a><br><a href="http://icedane.insomnia247.nl/secretlol/Effective%20STL.pdf">http://icedane.insomnia247.nl/secretlol/Effective%20STL.pdf</a><br><a href="https://www.geeksforgeeks.org/the-c-standard-template-library-stl/">https://www.geeksforgeeks.org</a><br><a href="https://www.javatpoint.com/cpp-templates">https://www.javatpoint.com/</a><br><a href="https://thispointer.com/how-stdvector-works-internally/">https://thispointer.com</a><br><a href="https://www.cs.helsinki.fi/u/tpkarkka/alglib/k06/lectures/containers.html">https://www.cs.helsinki.fi</a><br><a href="https://www.thecrazyprogrammer.com/2017/07/stl-array.html">https://www.thecrazyprogramme</a>r.com<br><a href="https://www.studytonight.com/cpp/stl/stl-container-list">https://www.studytonight.com</a><br><a href="https://appdividend.com/2019/06/12/cpp-list-tutorial-with-example-list-in-c-standard-template-library-stl/">https://appdividend.com</a><br><a href="https://alyssaq.github.io/stl-complexities/">https://alyssaq.github.io</a><br><a href="https://www.codeguru.com/cpp/cpp/cpp_managed/components/an-introduction-to-container-adapters-in-c.html">https://www.codeguru.com</a></p><h3>Okay, these are the beginner stuff.</h3><p><strong><em>Stay tuned for next iterator and algorithm part. Thank you guys for reading!! </em></strong>🙃</p><h3><strong>If you enjoyed this article, please click the 👏 button and share this article with others! Also, feel free to leave a comment below.</strong></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56d3f865a429" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into C++ STL | Part 1 |Containers]]></title>
            <link>https://medium.com/@smi.mandhare29/deep-dive-into-c-stl-part-1-containers-446eab728d4?source=rss-c35ccae81f03------2</link>
            <guid isPermaLink="false">https://medium.com/p/446eab728d4</guid>
            <dc:creator><![CDATA[smita mandhare]]></dc:creator>
            <pubDate>Sun, 31 May 2020 17:23:40 GMT</pubDate>
            <atom:updated>2020-05-31T17:32:58.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/96/0*cMeQ8XhSNun-H-L0.jpeg" /></figure><p><strong><em>Hope you are safe and doing great..!!</em></strong></p><p>C++ got lots of additions in C++11, C++14, C++17 and more recently C++20. By now, it is completely different compared to what it was a decade ago. The C++ standard does not only standardize the language, as it needs to be understood by compilers, but it also standardizes the STL (Standard Template Library).</p><p>To go through this article, I am assuming you have hands-on experience with C++ or have worked with at least one Object Oriented Programming Language.</p><p>While developing any application in C++, STL plays an important role. The internet is full of resources to learn STL but most of them are explained with amature examples. They explain how to use STL with simple data types but they don’t go that extra mile to give examples with classes and pointers. In the real world of C++ Application Development, STL is going to be used with classes and pointers only. In this article, you’re gonna learn how to use STL with classes and pointers.</p><p>What?</p><p>Pointers?? 😰</p><p>🏃‍♀️🏃‍♀️🏃‍♀️🏃‍♀</p><p>Wait, wait… don’t run away! 😃</p><p>Pointers are NOT as complicated as they seem to be. Once you start coding with C++, you’ll get used to pointers in no time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*ApenVLghULEXzdX0" /></figure><h3><strong>Little Introduction to STL</strong></h3><p>Before understanding how STL works with any class object, you must be asking how can map store int or any other class object? Well, there must be some generic code which handles any data type.</p><p>STLs are implemented based on generic template code. Let’s understand it step by step.</p><p>A template is a simple and yet very powerful tool in c++. The simple idea is to pass data types as parameters so that we don’t need to write some code for different data types. C++ provides two types of templates.</p><p><strong>typename</strong> indicates data type. Let’s go through the following code to understand the function template.</p><p>STLs are implemented using class templates.Suppose we defined mypair as a new data type.</p><p><strong>mypair</strong> can take any class object.</p><p>As you’ve got some idea on how STL works with any class, now we can dive into its usage in real applications, its time complexity and how it’s stored in memory. But first, let’s look at the main features of STL.</p><p>STL can be divided into 3 main features:</p><h3>1. Containers</h3><p><strong>2. Iterators</strong> <strong>3. Algorithms</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/0*Gt08MFPcsQgEtgRZ" /></figure><p>Algorithm types</p><p>In this part our focus will be on <strong>Containers.</strong></p><p>Containers</p><p><em>What is a Container?</em></p><p>“An STL Container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows a great flexibility in the types supported as elements.” — — — <em>cplusplus.com</em></p><p><em>Why the name Sequence?</em></p><p>Sequential containers implement data structures which can be accessed sequentially.</p><p>Let’s look into each Sequential Container <em>sequentially. </em>😎</p><p>array&lt;datatype, size&gt; arrayName;</p><p>array&lt;int,5&gt; marks = {87, 98, 70, 90, 100};</p><p><strong>Size of an array is Fixed.</strong></p><ul><li>C-style arrays don’t know their own size. But Array Containers know their own size. So when passing an array to a function, we don’t need to pass it’s size unlike we do in C-type arrays.</li><li>C-style arrays worked and entirely accessed by pointers whereas Array Containers are not.</li><li>Array Containers have more inbuilt functions than C-style arrays. So these are more efficient.</li></ul><p>Let’s implement it in class.</p><p><em>Problem statement: There is a library of school staff consisting of 100 persons which is constant and not going to change. Write code where the system can show which person has numbers of a specific book category. Here only consider learning the array concept, as code is written instantly, not a standard code like in an application. Here we’re using the index of the array as the id of the person.</em></p><pre>#include &lt;iostream&gt;int main()<br>#include &lt;array&gt; using namespace std; <br>{<br> <br> array &lt;library, 100&gt; staff; //all are initialized as zero initially<br> library person0(1,2,2);<br> staff[0] = person0;<br> cout &lt;&lt; staff[0];<br> library person1(1,0,1);<br> staff[1] = person1<br> library person5(3,1,1);<br> staff[5] = person5;<br> <br>}</pre><p>Here cout &lt;&lt; staff[0] will give error because &lt;&lt; operator is not defined. So below code is required as a member function.</p><ul><li>Vectors are dynamically sized arrays</li><li>Always prefer vectors over raw arrays</li></ul><p><strong>Declaration:</strong> <em>To declare an empty int array:</em></p><p>Vector &lt;int&gt; a</p><p><em>To declare a zero-initialized double “array” of size 50:</em></p><p>Vector &lt;double&gt; b(50)</p><p><em>To declare an int “array” of size n, with element initialized to 10:</em></p><p>Vector &lt;int&gt; (n,10)</p><p>- <em>Unlike arrays, vectors are aware of their size.</em></p><p>Vector &lt;int&gt; v1{1,4,2,8}</p><p>Cout &lt;&lt; v1.size(); // 4</p><p>- <em>When there is no capacity left, an additional memory of size 2 times the original capacity is allocated. The capacity is now doubled and the data is moved to the newly allocated memory. Push_back is used to append an element at the end in a vector.</em></p><p>v1.push_back(5);</p><p>Size indicates numbers in vectors and capacity is how much can be stored. Here now the vector size will increase from 4 to 8. (2n times)</p><p>Suppose vector is v2 of type int:</p><p>Vector &lt;int&gt; v2 = {1,2,3,4,5}</p><pre>for(int i =0; i &lt;v2.size();i++)<br> Cout &lt;&lt; v2[i] &lt;&lt; endl;</pre><p>2. Using iterator // will discuss later</p><pre>for(vector&lt;int&gt;iterator::it = v2.begin(); it !=v2.end();it++)<br> Cout &lt;&lt; *it &lt;&lt; endl;</pre><p>3. Using ranged-based loop</p><p>Vector has it’s own public member functions to utilize it.</p><p>Let’s see how it is use with classes Inventory is class with 3 private members:</p><ol><li>Size — Recently we has used size which gives numbers of elements in container</li><li>Capacity — returns size allocated to vector</li><li>Push_back — add element at end of vector</li></ol><p><em>Problem : has 3 memory of different branch shoes, bandminton, and playerId. shop1 will have different brands of above things. Numbers of different brand may be change at run time.</em></p><pre>#include &lt;iostream&gt; ~inventory() vector &lt;inventory&gt; shop1; inventory *pionterToObject3;<br>#include &lt;vector&gt; using namespace std; <br> {<br> <br> }<br> shop1.push_back(object1);<br> shop1.push_back(object2); <br> pionterToObject3 = &amp;object3;<br> shop2.push_back(pionterToObject3); <br> <br> void SetAllParam(int shoes,int bandminton, int playerId)<br> {<br> this-&gt;shoes = shoes;<br> this-&gt;bandminton = bandminton;<br> this-&gt;playerId = playerId;<br> } //Initialise vector object push_back is fun use to add element in vector //to store pointer vector</pre><p>How does vector works internally?</p><p>std::vector allocates a memory on heap and store all its elements in contiguous memory location.</p><p>But what if memory it allocated initially is completely filled?</p><p>For example, let’s create a vector of int i.e. std::vector&lt;int&gt; . Now suppose it’s initial capacity is to store 10 elements, but in our application we want to store 15 elements in it. Then what will happen when we will insert 11th element?</p><p>When std::vector’s internal memory completely finishes then it increases the size of its memory. To do that it performs following steps,</p><p>1.) It will allocate a bigger chunk of memory on heap i.e. almost double the size of previously allocated.</p><p>2.) Then it copies all the elements from old memory location to new one. Yes it copies them, so in case our elements are user defined objects then their copy constructor will be called. Which makes this step quite heavy in terms of speed.</p><p>3.) Then after successful copying it deletes the old memory.</p><p>You can check the current capacity of vector i.e. how much elements it can store in current allocated memory using capacity() member function.</p><p>Time Complexity:</p><p>If we create a new double sized array whenever current array becomes full (or it is about to become full), and copy current elements to new double sized array, we get amortized time complexity as O(1). So a particular insert operation may be costly, but overall time complexity remains O(1). Since erasing an element requires moving other elements (to ensure random access), time complexity of erase is O(1)</p><p>List is a container that supports constant time insertion and removal of elements from anywhere in the container. Fast random access is not supported. It is usually implemented as a doubly-linked list. Doubly linked lists can store each of the elements, they contain in different and unrelated storage locations. The ordering is kept internally by the association to each element of a link to the element preceding it and a link to the element following it.</p><p>They are very similar to <a href="http://www.cplusplus.com/forward_list">forward_list</a>: The main difference being that <a href="http://www.cplusplus.com/forward_list">forward_list</a> objects are single-linked lists, and thus they can only be iterated forwards, in exchange for being somewhat smaller and more efficient.</p><p>Compared to other base standard sequence containers ( <a href="http://www.cplusplus.com/array">array</a>, <a href="http://www.cplusplus.com/vector">vector</a> and <a href="http://www.cplusplus.com/deque">deque</a>), lists perform generally better in inserting, extracting and moving elements in any position within the container for which an iterator has already been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms.</p><p>The main drawback of lists and <a href="http://www.cplusplus.com/forward_list">forward_list</a> s compared to these other sequence containers is that they lack direct access to the elements by their position; For example, to access the sixth element in a list, one has to iterate from a known position (like the beginning or the end) to that position, which takes linear time in the distance between these. They also consume some extra memory to keep the linking information associated to each element (which may be an important factor for large lists of small-sized elemets).</p><ul><li>Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by their position in this sequence.</li><li>Implements bidirectional linked list</li><li>Each element keeps information on how to locate the next and the previous elements, allowing constant time insert and erase operations before or after a specific element (even of entire ranges), but no direct random access.</li><li>The container uses an allocator object to dynamically handle its storage needs.</li><li>syntax : list &lt;dataType&gt; obj;</li></ul><p>can conclude below points:</p><p>Elements of the list can be scattered in the different chunks of memory. Container stores the necessary information to allow sequential access to its data.</p><p>C++ Lists can shrink or expand as needed from both ends at run time. The storage requirement is fulfilled automatically by the internal allocator.</p><p>Zero-sized lists are also valid. In that case <strong>list.begin()</strong> and <strong>list.end()</strong> points to the same location. But the behavior of calling front() or back() is undefined.</p><p>std::list does not have random access operator [] because std::list internally store elements in doubly linked list. So, to access an element at nth location we need to iterate one by one from beginning to nth element. So, its complexity will be O(n).</p><p>Suppose we have a list of strings i.e.</p><p>Now lets see how to access element at 3rd position from list using 2 different techniques.</p><pre>template &lt;class InputIterator, class Distance&gt;<br>void advance (InputIterator&amp; it, Distance n);</pre><p>As iterator <strong>it</strong> was already pointing to first element, therefore we need to advance it by 2 to point it to 3rd position.</p><p>Complexity of std::advance for std::list is O(n) because it needs to iterate one by one from beginning to nth position.</p><p>In C++11 another algorithm has been introduced i.e std::next().</p><p>std::next() is introduced in C++11. It accepts an iterator and position to be advanced. It does not modify the passed iterator, but uses it to create a new iterator pointing to nth -1 position from given iterator and returns it.</p><p>Lets see how to access element at 3rd position by std::next()</p><p>auto it1 = std::next(listOfStrs.begin(), 2);</p><p>Problem Statement: Write a program where one element has port and priority, another sub-element has host and weight. write a code where, sub-system dynamically add element.</p><pre>class TheElement<br>{<br> <br> public:<br> TheElement(){mport = 0; mpriority = 0;}<br> TheElement(int port, bool priority) { mport = port; mpriority = false;}<br>~TheElement() { }<br> <br> private:<br> int mport;<br> bool mpriority; <br>};</pre><p>Deque is a double ended queue container that provides insertion and deletion at both ends i.e. front and back with<br>high performance unlike vector that provides high performance insertion at end i.e. back only.</p><p>Also it provides random access to elements just like a vector. Although one can insert an element in between other elements in dequeue with insert() function, but its performance will not be good just like vector.</p><p>Inserting an element in front of deque push_front is used. push_back is used to insert element at end. pop_front is used to remove element from front and pop_back used to remove from back of queue.</p><p>How deque is work internally?</p><p>Now a question rises how high deque is able to give good performance for insertion and deletion at both ends?<br>To know the answer we need to know little internal implementation of dequeue.</p><p>A deque is generally implemented as a collection of memory blocks. These memory blocks contains the elements at contiguous locations.</p><ul><li>When we insert an element in end it stores that in allocated memory block untill it gets filled and when this memory block gets filled with elements then it allocates a new memory block and links it with the end of previous memory block. Now further inserted elements in the back are stored in this new memory block.</li><li>When we insert an element in front it allocates a new memory block and links it with the front of previous memory block. Now further inserted elements in the front are stored in this new memory block unless it gets filled.</li><li>Consider deque as a linked list of vectors i.e. each node of this linked list is a memory block that store elements at contiguous memory location and each of the memory block node is linked with its previous and next memory block node.</li></ul><p>When we create a deque object it internally allocates a memory block to store the elements at contigious location.</p><p><em>Problem Statement: Write a program to push 2 elements from the front end and 2 elements from the back end and print the deque.</em></p><p>Therefore, insertion at front is fast as compared to vector because it doesn’t need the elements to shift by 1 in current memory block to make space at front. It just checks if any space is left at left of first element in current memory block, if not then allocates a new memory block.</p><p>why name associative?</p><p>because they associate <em>keys</em> with <em>values</em>. Well, at least <strong>map</strong>s and <strong>multimap</strong>s associate keys with values, but you can look at a <strong>set</strong> as a <strong>map</strong> that has no values, only keys.</p><ul><li>It’s doesn’t allow duplicate elements i.e. it only contains unique elements.</li><li>Std::set can contain element of any specified type in template argument i.e.</li></ul><p>Set is a container implemented in C++ language in STL and has a concept similar to how set is defined in mathematics. The facts that separates set from the other containers is that is it contains only the <strong>distinct elements</strong> and elements can be traversed in sorted order. Having the strong hold on sets is useful in competitive programming and solving algorithmic problems.</p><ul><li>std::set internally store elements in balanced binary tree.</li><li>By default std::set uses the operator &lt; for comparing two elements and but if user passes the external sorting criteria i.e. comparator then it uses that instead of default operator &lt;.</li><li>std::set will keep the inserted elements in sorted order based on the assigned sorting criteria i.e. either by default criteria operator &lt; or by passed comparator (if passed).</li></ul><pre>std::set&lt;int&gt; // contains only int elements.<br>class Sample;<br>std::set&lt;Sample&gt; // contains only Sample class objects.</pre><p>public member function :</p><p>std:: <a href="http://www.cplusplus.com/reference/set/set/">set</a>::key_comp</p><p><strong>Return comparison object</strong></p><pre>key_compare key_comp() const;</pre><p>Returns a copy of the <em>comparison object</em> used by the container.</p><p>By default, this is a <a href="http://www.cplusplus.com/less">less</a> object, which returns the same as operator&lt;.</p><p>This object determines the order of the elements in the container: it is a function pointer or a function object that takes two arguments of the same type as the container elements, and returns true if the first argument is considered to go before the second in the <em>strict weak ordering</em> it defines, and false otherwise.</p><p>Two elements of a <a href="http://www.cplusplus.com/set">set</a> are considered equivalent if key_comp returns false reflexively (i.e., no matter the order in which the elements are passed as arguments).</p><p>In <a href="http://www.cplusplus.com/set">set</a> containers, the keys to sort the elements are the values themselves, therefore key_comp and its sibling member function <a href="http://www.cplusplus.com/set::value_comp">value_comp</a> are equivalent.</p><p><strong>Inserting element into set:</strong></p><p>The comparison object.<br>Member type key_compare is the type of the <em>comparison object</em> associated to the container, defined in <a href="http://www.cplusplus.com/set">set</a> as an alias of its second template parameter (Compare).</p><p>There are different ways we can insert elements into set.</p><p><strong>Note:</strong> In any method below when we insert an element into set it automatically inserted at proper position based on ascending sorted order.</p><p><strong>Method 1:</strong> Insert directly by passing element. <strong>setName.insert(element);</strong></p><p><strong>Method 2:</strong> Using iterator. This returns iterator at inserted position. <strong>setName.insert (iterator,value)</strong></p><p><strong>Method 3:</strong> Copying from another container.</p><p>Can you guess output of following code</p><p>It will give compilation Error. How???</p><p>let’s rewind definition of set. It has distict elements hence no duplicate allowed and it is in sorted form. For sorting it has operator &lt; overloaded operator. here it is not defined in class. hence program will give following error:</p><p>let’s add defination of &lt; operator in class as below:</p><p>There is another set called <strong>unorderd_set</strong> where duplicate keys are not allowed but it is not in sorted.</p><p>Multisets are a type of associative containers similar to set, with an exception that multiple elements can have same values.</p><p>Internally, the elements in a multiset are always sorted following a specific <em>strict weak ordering</em> criterion indicated by its internal <a href="http://www.cplusplus.com/multimap::key_comp">comparison object</a> (of type Compare).</p><p>multiset containers are generally slower than <a href="http://www.cplusplus.com/unordered_multiset">unordered_multiset</a> containers to access individual elements by their <em>key</em>, but they allow the direct iteration on subsets based on their order.</p><p>Multisets are typically implemented as <em>binary search trees</em>.</p><pre>#include &lt;iostream&gt;<br>#include &lt;set&gt; using namespace std;</pre><p>There is another set called <strong>unorderd_multiset</strong> where duplicate keys are allowed but it is not in sorted.</p><p>why name adapter container?</p><p>Each of these “adaptors container “ is constructed by taking one of the sequential containers given above and “adapting” (restricting/modifying) its interface to provide the desired behavior.</p><p>Being in software development, we are pretty known to stack. It is same as stack data structure.</p><p>It is a simple data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the <strong>top</strong> of the stack and the only element that can be removed is the element that is at the top of the stack, just like a pile of objects.</p><p><strong>stack</strong>s are implemented as <em>container adaptors</em>, which are classes that use an encapsulated object of a specific container class as its <em>underlying container</em>, providing a specific set of member functions to access its elements. Elements are <em>pushed</em>/ <em>popped</em> from the <em>“back”</em> of the specific container, which is known as the <em>top</em> of the stack.</p><p>The underlying container may be any of the standard container class templates or some other specifically designed container class. The container shall support the following operations:</p><p><em>Problem Statement: scheduler has to be defined where there is numbers of tasks with equal priority. top most task will be served first and will be removed.</em></p><p>The standard container classes <a href="http://www.cplusplus.com/vector">vector</a>, <a href="http://www.cplusplus.com/deque">deque</a> and <a href="http://www.cplusplus.com/list">list</a> fulfill these requirements. By default, if no container class is specified for a particular stack class instantiation, the standard container <a href="http://www.cplusplus.com/deque">deque</a> is used.</p><pre>#include &lt;iostream&gt;<br>#include &lt;stack&gt; using namespace std;</pre><p>The std::queue class is a container adapter that gives the programmer the functionality of a queue — specifically, a FIFO (first-in, first-out) data structure.</p><p>The class template acts as a wrapper to the underlying container — only a specific set of functions is provided. The queue pushes the elements on the back of the underlying container and pops them from the front.</p><p>Taking is same example which we are learned from engineering. 😜</p><p>If you stand in a queue at a grocery store (or anywhere else), the first customer in the queue will be served, and then the next, and so on.</p><p>How queue is implemented?</p><p>There is good example on <a href="https://www.techiedelight.com/">https://www.techiedelight.com/</a> related to queue. Below code is taken from the same:</p><pre>#include &lt;iostream&gt;// define default capacity of the queuepublic:front = (front + 1) % capacity;// Utility function to return front element in the queue<br>#include &lt;cstdlib&gt;<br>#define SIZE 10 <br> queue(int size = SIZE); // constructor<br> ~queue(); // destructor <br> count--;<br>} <br>int queue::peek()<br>{<br> if (isEmpty())<br> {<br> cout &lt;&lt; &quot;UnderFlow\nProgram Terminated\n&quot;;<br> exit(EXIT_FAILURE);<br> }<br> return arr[front];<br>} <br>using namespace std; cout &lt;&lt; &quot;Removing &quot; &lt;&lt; arr[front] &lt;&lt; &#39;\n&#39;; cout &lt;&lt; &quot;Inserting &quot; &lt;&lt; item &lt;&lt; &#39;\n&#39;; cout &lt;&lt; &quot;Queue size is &quot; &lt;&lt; q.size() &lt;&lt; endl;</pre><p>Let’s take same example as above queue.</p><p>In a priority queue, apart from the FIFO characteristics, certain customers (or elements in a queue) might have a higher priority, and they might receive immediate service irrespective of their location in the queue.</p><ol><li>Every item has a priority associated with it.</li><li>An element with high priority is dequeued before an element with low priority.</li><li>If two elements have the same priority, they are served according to their order in the queue.</li></ol><p>Priority Queue is an extension of <a href="http://quiz.geeksforgeeks.org/queue-set-1introduction-and-array-implementation/">queue </a>with following properties.</p><p>A typical priority queue supports following operations.<br><strong>insert(item, priority): </strong>Inserts an item with given priority.<br><strong>getHighestPriority():</strong> Returns the highest priority item.<br><strong>deleteHighestPriority(): </strong>Removes the highest priority item.</p><p>In a queue, the <strong>first-in-first-out rule</strong> is implemented whereas, in a priority queue, the values are removed <strong>on the basis of priority</strong>. The element with the highest priority is removed first.</p><p>When reading about priority queues, didn’t their ability to retrieve the largest element reminded you of something?</p><p>Heaps, of course!</p><p>Indeed, in heaps basics we saw that they offer an easy access to the largest elements, by positioning it at their root.</p><p>In fact, the relationship between heaps and priority queues is even closer than that: <strong>heaps are an implementation of priority queues</strong>.</p><p>Indeed, in a heap we can add data, and access and remove the largest element, so they can implement the interface of a priority queue. Let’s see this in more details.</p><p>Let’s consider the following heap (implemented as an array):</p><pre>std::vector&lt;double&gt; numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; std::make_heap(begin(numbers), end(numbers));</pre><p>Let’s see how to perform the main functions of the interface of a priority queue with the STL algorithms on heaps.</p><h3>Adding an element</h3><p>In a priority queue we need to be able to add an element with the push method.</p><p>Let’s add the new element 4.12. Here is how to do it by using the STL algorithms on heap:</p><pre>numbers.push_back(4.12);<br>std::push_heap(begin(numbers), end(numbers));</pre><h3>Accessing the largest element</h3><p>In a priority queue, we need to access the largest element with the top method. It is located at the beginning of the array and can be accessed in constant time with:</p><pre>numbers.front()</pre><h3>Removing the largest element</h3><p>Finally, a priority queue needs to be able to remove its largest element with its pop method. The algorithm pop_heap moves the first element of the array to its end and rearranges the other elements into a heap:</p><pre>std::pop_heap(begin(numbers), end(numbers)); // 9 is at the end<br>numbers.pop_back(); // 9 is gone, 8 is the new top</pre><p>To sum this all up:</p><p>Priority queues can be implemented by heaps and heaps can be implemented by arrays.</p><p>References:</p><p><a href="http://www.cplusplus.com/doc/oldtutorial/templates/">http://www.cplusplus.com</a><br><a href="https://discourse-production.oss-cn-shanghai.aliyuncs.com/original/3X/c/e/ce2e1fe51865660aaa835bd2674c1920e49f4c82.pdf">https://discourse-production.oss-cnshanghai.aliyuncs.com/original/3X/c/e/ce2e1fe51865660aaa835bd2674c1920e49f4c82.pdf</a><br><a href="https://www.dre.vanderbilt.edu/~schmidt/PDF/STL.pdf">https://www.dre.vanderbilt.ed</a>u<br><a href="http://assets.hkoi.org/training2017/cppstl.pdf">http://assets.hkoi.org/training2017/cppstl.pdf</a><br><a href="http://icedane.insomnia247.nl/secretlol/Effective%20STL.pdf">http://icedane.insomnia247.nl/secretlol/Effective%20STL.pdf</a><br><a href="https://www.geeksforgeeks.org/the-c-standard-template-library-stl/">https://www.geeksforgeeks.org</a><br><a href="https://www.javatpoint.com/cpp-templates">https://www.javatpoint.com/</a><br><a href="https://thispointer.com/how-stdvector-works-internally/">https://thispointer.com</a><br><a href="https://www.cs.helsinki.fi/u/tpkarkka/alglib/k06/lectures/containers.html">https://www.cs.helsinki.fi</a><br><a href="https://www.thecrazyprogrammer.com/2017/07/stl-array.html">https://www.thecrazyprogramme</a>r.com<br><a href="https://www.studytonight.com/cpp/stl/stl-container-list">https://www.studytonight.com</a><br><a href="https://appdividend.com/2019/06/12/cpp-list-tutorial-with-example-list-in-c-standard-template-library-stl/">https://appdividend.com</a><br><a href="https://alyssaq.github.io/stl-complexities/">https://alyssaq.github.io</a><br><a href="https://www.codeguru.com/cpp/cpp/cpp_managed/components/an-introduction-to-container-adapters-in-c.html">https://www.codeguru.com</a></p><p><strong><em>Stay tuned for next iterator and algorithm part. Thank you guys for reading!! </em></strong>🙃</p><p><em>Originally published at </em><a href="https://medium.com/@smi.mandhare29/deep-dive-into-c-stl-part-1-containers-56d3f865a429"><em>https://medium.com</em></a><em> on May 31, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=446eab728d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>