    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Introduction to STL (Standard Template Library)</title>
        <link>https://members.accu.org/index.php/articles/695</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + CVu Journal Vol 16, #5 - Oct 2004</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c100/">165</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-100/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+100/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Introduction to STL (Standard Template Library)</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 03 October 2004 13:16:08 +01:00 or Sun, 03 October 2004 13:16:08 +01:00</p>
<p><strong>Summary:</strong>&nbsp;<p>Since STL is a very large topic to be covered in an article or two, we will focus on the most commonly used generic classes: vector and string.</p></p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a></h2>
</div>
<div class="blockquote">
<blockquote class="blockquote">
<p>A template is defined as &quot;something that establishes or serves
as a pattern&quot; Websters</p>
</blockquote>
</div>
<p>In C++, a template has more or less the same meaning. A template
is like a skeleton code which becomes &quot;<span class=
"emphasis"><em>alive</em></span>&quot; when it is instantiated with a
type.</p>
<p>An algorithm is a <span class="emphasis"><em>well-ordered
collection of unambiguous and effectively computable operations
that when executed produces a result and halts in a finite amount
of time</em></span> [<a href="#Schneider">Schneider</a>].</p>
<p>A class holding a collection of elements of some type is
commonly called a <span class="emphasis"><em>container
class</em></span>, or simply a <span class=
"emphasis"><em>container</em></span> [<a href=
"#Stroustrup">Stroustrup</a>].</p>
<p>A class is a user defined type which is very similar to the
pre-defined types like <tt class="type">int</tt>, <tt class=
"type">char</tt>, etc. So, the standard template library (STL) is a
collection of generic algorithms and containers which are
orthogonal to each other. By the word orthogonal, we mean that any
algorithm can be used on any container and vice-versa.</p>
<p>In C++, there are various generic classes like <tt class=
"classname">vector</tt>, <tt class="classname">string</tt>,
etc.</p>
<p>Since STL is a very large topic to be covered in an article or
two, we will focus on the most commonly used generic classes:
<tt class="classname">vector</tt> and <tt class=
"classname">string</tt>. Before we discuss the standard containers
let us take a simple example to understand the word <span class=
"emphasis"><em>template</em></span>.</p>
<pre class="programlisting">
// template.cpp

#include&lt;iostream&gt;
using std::cout;

template&lt;typename T&gt;
         // Declares T as a name of some type
/* It is also common to see template&lt;class T&gt;.
   The two mean the same */

/* The following template defines a function
   which takes two constant references of type
   T and returns the maximum value of type T.
   */

T Max(const T&amp; a, const T&amp; b) {
  return (a &gt; b)? a : b;
}

int main() {
  cout &lt;&lt; Max('i', 'r') &lt;&lt; &quot;\n&quot;;
  cout &lt;&lt; Max(1, 3) &lt;&lt; &quot;\n&quot;;
}
</pre>
<pre class="screen">
// Output of template.cpp
r
3
</pre>
<p>In the above example, a function <tt class="function">Max</tt>
is defined which takes two constant references of type <tt class=
"type">T</tt> and returns the maximum value. But in the <tt class=
"function">main</tt> function there are two function calls, one is
<tt class="function">Max('i','r')</tt> and the other one is
<tt class="function">Max(1,3)</tt>. We did not get any compilation
errors because we have used the template mechanism in this
function. At run-time, the compiler resolves what types are being
passed to the <tt class="function">Max</tt> function and hence
knows which output to return. It should be noted that the final
compiled binary will be larger as the compiler has to create a
function for every type in the code passed to it.</p>
<p>Now, let us start with the example of the <tt class=
"classname">vector</tt> container.</p>
<p>A <tt class="classname">vector</tt> is very similar to an array
but has more advanced features, some of which are utilized in the
example below.</p>
<pre class="programlisting">
#include&lt;iostream&gt;
#include&lt;vector&gt;

using namespace std;

int main() {
  /* I'll now create a vector of integers. It
     is instantiated here, so vint can hold
     integers */
  vector&lt;int&gt; vectorint;
  vectorint.reserve(5);

  /* reserve pre-allocates memory for holding
     five integers*/

  for(int j = 1; j &lt; 6; j++)
    vectorint.push_back(j);

  typedef vector&lt;int&gt; Vector_Of_Ints;
  for(Vector_Of_Ints::const_iterator i
                             = vint.begin();
      i != vint.end(); ++i)
    cout &lt;&lt; *i &lt;&lt; &quot;\t&quot;;
    cout &lt;&lt; endl;
}
</pre>
<p>It should be noted that the <tt class="methodname">reserve</tt>
function allocates memory but the allocation is more akin to that
of an array than using new. The capacity of a vector is defined as
the <span class="emphasis"><em>minimum number of objects that it
can hold</em></span>. The reserve method makes sure that the vector
has a capacity <span class="emphasis"><em>greater than or equal to
its argument</em></span> [<a href="#Sutter">Sutter</a>]. In the
above example, after this statement</p>
<pre class="programlisting">
vectorint.reserve(5);
</pre>
<p>the <tt class="classname">vector</tt> <tt class=
"varname">vectorint</tt> has a capacity of at least 5.</p>
<p>The <tt class="methodname">push_back()</tt> method function
pushes the five integers into the <tt class=
"classname">vector</tt>. An iterator behaves in the same way as a
pointer but is more generic. Note that the iterator is made a
constant in this example because an iterator seldom modifies the
contents of its <tt class="classname">vector</tt>.</p>
<p>In the above example, <tt class=
"methodname">vectorint.begin()</tt> points to the first element of
the <tt class="classname">vector</tt>, which is 1. <tt class=
"methodname">vectorint.end()</tt> points to an element which is
after the last element of the <tt class="classname">vector</tt>,
which is 5 in this case. Therefore, we cannot dereference
<tt class="methodname">vectorint.end()</tt>. This is as shown
below:</p>
<p>When we dereference the iterator using the <tt class=
"methodname">*</tt> operator, we get the value stored at the
address to which the iterator points to.</p>
<div class="c2"><img src=
"resources/Introduction%20to%20STL%20figure%201.png" align=
"middle"></div>
<p>When the above code is executed, gives the following output:</p>
<pre class="screen">
1    2    3    4    5
</pre>
<p>An even more convenient way of printing a <tt class=
"classname">vector</tt> would be to use the copy algorithm as shown
below:</p>
<pre class="programlisting">
copy(vint.begin(), vint.end(),
     ostream_iterator&lt;int&gt;(cout, &quot;    &quot;));
</pre>
<p>which basically means: <span class="emphasis"><em>copy the
contents of the</em></span> <tt class="classname">vector</tt>
<span class="emphasis"><em>starting from</em></span> <tt class=
"methodname">vint.begin()</tt> <span class=
"emphasis"><em>to</em></span> <tt class=
"methodname">vint.end()</tt> <tt class="literal">-1</tt>
(<span class="emphasis"><em>remember that</em></span> <tt class=
"methodname">vint.end()</tt> <span class="emphasis"><em>points to
an element <span class="bold"><b>after</b></span> the last element
of the</em></span> <tt class="classname">vector</tt>) <span class=
"emphasis"><em>to the standard output</em></span> (<tt class=
"classname">cout</tt>) <span class="emphasis"><em>separating each
of the numbers with four space characters</em></span>.</p>
<p>The header <tt class="filename">&lt;algorithm&gt;</tt> must be
included for the copy algorithm to work.</p>
<p>Of course, the <tt class="classname">vector</tt> can be of any
type, <tt class="type">int</tt>, <tt class="type">char</tt> or even
another class such as <tt class="classname">string</tt>, and they
are all handled in the same way. This is possible because a
<tt class="classname">vector</tt> is a generic container, or in
other words, a <tt class="classname">vector</tt> is a template
class. For example after the statement</p>
<pre class="programlisting">
vector&lt;T&gt; foo;
</pre>
<p><tt class="classname">foo</tt> can hold objects of type
<tt class="type">T</tt>. Therefore, <tt class="type">T</tt> can
even be any class.</p>
<p>Consider a normal class <tt class="classname">foo</tt>. It will
have a standard constructor, destructor, some methods, and a couple
of variables.</p>
<pre class="programlisting">
class foo {
public:
  foo();
  foo(int a, int b);
  foo(int a, double b);
  ~foo() {};
  int showValue() {
    return something;
  }
private:
  int something;
};
</pre>
<p>A template class can be thought of as being the same, except
that now when we instantiate it, we do so with an unspecified type
<tt class="type">T</tt> rather than an explicit <tt class=
"type">int</tt>, <tt class="type">char</tt>, etc. Everything else
remains the same (more or less).</p>
<pre class="programlisting">
template &lt;typename A, typename B&gt;
class foo {
public:
  foo();
  foo(A a, A b);
  foo(A a, B b);
  ~foo() {};
  A showValue() {
    return something;
  }
private:
  A something;
};
</pre>
<p>Next let us consider the <tt class="classname">string</tt>
class. A <tt class="classname">string</tt> container is very
similar to that of a <tt class="classname">vector</tt> class. A
<tt class="classname">string</tt> object can be declared as
follows:</p>
<pre class="programlisting">
std::string sobject;
</pre>
<p>A <tt class="classname">string</tt> object can be initialized in
some of the following ways (there are plenty of other ways)</p>
<div class="orderedlist">
<ol type="1">
<li>
<p><tt class="literal">string sobject(&quot;hello&quot;);</tt></p>
</li>
<li>
<p><tt class="literal">string sobject = &quot;hello&quot;;</tt></p>
</li>
<li>
<p><tt class="literal">string s1 = &quot;Hello, &quot;;</tt></p>
</li>
<li>
<p><tt class="literal">string sobject = s1;</tt></p>
</li>
<li>
<p><tt class="literal">string s2 = &quot;World&quot;;</tt></p>
</li>
<li>
<p><tt class="literal">string sobject =s1 + s2;</tt></p>
</li>
</ol>
</div>
<p>In the first form of initialization the constructor of the
<tt class="classname">string</tt> class is invoked with the value
of &quot;<tt class="literal">hello</tt>&quot; and therefore the <tt class=
"varname">sobject</tt> has the value of &quot;<tt class=
"literal">hello</tt>&quot; once this line is executed.</p>
<p>In the second, third and fifth forms of initialisation, a
<tt class="classname">string</tt> is assigned to the <tt class=
"classname">string</tt> object and so the <tt class=
"classname">string</tt> objects will hold the respective strings
after these statements are executed.</p>
<p>In the fourth and fifth form of initialization, the copy
constructor of the <tt class="classname">string</tt> class is
invoked in order to copy the contents of the strings at the right
hand side to the <tt class="classname">string</tt> objects.</p>
<p>Let us take another example which uses both the <tt class=
"classname">string</tt> and <tt class="classname">vector</tt> class
to understand how both of them work together.</p>
<pre class="programlisting">
// vecstringSimple.cpp

#include&lt;iostream&gt;
#include&lt;string&gt;
#include&lt;vector&gt;
#include&lt;iterator&gt;

using namespace std;

int main() {
  vector&lt;string&gt; vector_of_strings;
  vector_of_strings.reserve(5);
  string text;
  cout &lt;&lt; &quot;\n&quot;;
  cout &lt;&lt; &quot;Enter the strings\n&quot;;
  cout &lt;&lt; &quot;\n&quot;;
  for (int a = 0; a &lt; 5; ++a) {
    cin &gt;&gt; text;
    vector_of_strings.push_back(text);
  }

  cout &lt;&lt; &quot;\n&quot;;
  cout &lt;&lt; &quot;Output of the program\n&quot;;
  cout &lt;&lt; &quot;\n&quot;;
  for(vector&lt;string&gt;::iterator i
            = vector_of_strings.end()-1;
      i &gt;= vector_of_strings.begin();
      i--)
    cout &lt;&lt; *i &lt;&lt; &quot;\n&quot;;
}
</pre>
<p>In the above example a <tt class="classname">vector</tt> of
<tt class="classname">string</tt>s is created and <tt class=
"classname">string</tt>s are read into the <tt class=
"classname">vector</tt> until the input is end. The <tt class=
"classname">string</tt>s are then output in the reverse order in
which they were entered, as shown below</p>
<pre class="screen">
Enter the strings:

Rajanikanth
Ravikanth
Srimannarayana
VijayaLakshmi
hello

Output of the program:

hello
VijayaLakshmi
Srimannarayana
Ravikanth
Rajanikanth
</pre>
<p>Let us take a more complex example which uses both the
<tt class="classname">string</tt> and <tt class=
"classname">vector</tt> classes.</p>
<pre class="programlisting">
// vecstr.cpp

#include&lt;iostream&gt;
#include&lt;vector&gt;
#include&lt;algorithm&gt;
#include&lt;iterator&gt;
#include&lt;string&gt;

using namespace std;

int main() {
  vector&lt;string&gt; vector_of_strings;
  string s;

  cout &lt;&lt; &quot;Enter the strings to be sorted: &quot;
       &lt;&lt; &quot;\n&quot;;

  while(getline(cin,s) &amp;&amp; s != &quot;end&quot;)
    vector_of_strings.push_back(s);

  sort(vector_of_strings.begin(),
       vector_of_strings.end());
  vector&lt;string&gt;::const_iterator pos
         = unique(vector_of_strings.begin(),
                  vector_of_strings.end());
  vs.erase(pos, vector_of_strings.end());
  copy(vector_of_strings.begin(),
       vector_of_strings.end(),
       ostream_iterator&lt;string&gt;(cout,
                                &quot;\t&quot;));
  cout &lt;&lt; '\n';
}
</pre>
<p>Let us first understand how this code works and then we will
look at how it runs.</p>
<p>First of all, the line</p>
<pre class="programlisting">
vector&lt;string&gt; vector_of_strings;
</pre>
<p>declares <tt class="varname">vector_of_strings</tt> as a
<tt class="classname">vector</tt> of <tt class=
"classname">string</tt>s.</p>
<p>Next, the condition</p>
<pre class="programlisting">
while(getline(cin,s) &amp;&amp; s != &quot;end&quot;)
</pre>
<p>means read a line of input from stdin as a <tt class=
"classname">string</tt> until the input is end. So, &quot;end&quot; cannot be
an input string for this program. Next, the program pushes each of
these <tt class="classname">string</tt>s into the <tt class=
"classname">vector</tt> <tt class=
"varname">vector_of_strings</tt>.</p>
<p>The algorithm sorts the <tt class="classname">string</tt>s in
the <tt class="classname">vector</tt> <tt class=
"varname">vector_of_strings</tt> in ascending order. The unique
algorithm moves all but the first <tt class="classname">string</tt>
for each set of consecutive <tt class="classname">string</tt>s to
the end of the unique set of <tt class="classname">string</tt>s in
the <tt class="classname">vector</tt> container. It returns an
iterator which points to the end of the unique set of <tt class=
"classname">string</tt>s; in our code this iterator is stored in
<tt class="varname">pos</tt>. Next, we call the <tt class=
"function">erase</tt> iterator which actually deletes the duplicate
elements from <tt class="varname">pos</tt> to <tt class=
"methodname">vector_of_strings.end()</tt>.</p>
<p>The <tt class="function">copy</tt> algorithm then copies the
unique set of <tt class="classname">string</tt>s to the standard
output.</p>
<p>Following is the output of the program <tt class=
"filename">vecstr.cpp</tt></p>
<pre class="screen">
Enter the strings to be sorted: 
Srimannarayana Jammalamadaka
VijayaLakshmi Jammalamadaka
Rajanikanth Jammalamadaka
Ravikanth Jammalamadaka
aaaaa
a
a
k
k
end

Rajanikanth Jammalamadaka
        Ravikanth Jammalamadaka
        Srimannarayana Jammalamadaka
        VijayaLakshmi Jammalamadaka
        a       aaaaa   k     
</pre>
<p>We will discuss a more complicated program using the <tt class=
"classname">vector</tt> and <tt class="classname">string</tt>
containers in the next article.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e498" id="d0e498"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Schneider" id="Schneider"></a>
<p class="bibliomixed">[Schneider] Schneider, M. and J. Gersting
(1995), <span class="citetitle"><i class="citetitle">An Invitation
to Computer Science</i></span>, West Publishing Company, New York,
NY, p. 9.</p>
</div>
<div class="bibliomixed"><a name="Stroustrup" id="Stroustrup"></a>
<p class="bibliomixed">[Stroustrup] Stroustrup, B., <span class=
"citetitle"><i class="citetitle">The C++ Programming Language
(Special Edition)</i></span>, Addison Wesley, p. 41.</p>
</div>
<div class="bibliomixed"><a name="Sutter" id="Sutter"></a>
<p class="bibliomixed">[Sutter] Sutter, H., <span class=
"citetitle"><i class="citetitle">Exceptional C++ Style : 40 New
Engineering Puzzles, Programming Problems, and Solutions (C++ in
Depth Series)</i></span>, Pearson Education; (July, 2004).</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
